Input innerhtml

hi everybody im new to this

what i have tot do is when i write a name in input the birthyear of the person i put in wil come, and when i put an other name then the year he is born wil come but its hard for me i cant do it this my code

**

 <script>

        function change(){
            
            var arrayName = ["bob", "john"];
            var arrayYear = ["1997", "1995"];
            
            var inp = document.getElementById("in");
            
            if(inp == arrayName[0]){
                document.getElementById("p").innerHTML = arrayYear[0];
            
            }else if(inp == arrayName[1]){
                document.getElementById("p").innerHTML = arrayYear[1];

            }
            
    }
       
        
    </script>

Welcome to the world of Javascript.

inp isnt what you think it is by the time it gets to the ==. (Hint: Input boxes have ‘value’, not ‘innerHTML’)

1 Like

sorry for this now but what do i have to do now?

Try this.

var inp = document.getElementById("in");

=>

var inp = document.getElementById("in").value;
1 Like

it doesnt read it it only says like nodevalue

ow wait sorry it works hahah thank you!

Hi @zouzi, welcome to JS indeed. :-) As a side note, you might simplify this a lot by using the Array .indexOf() method… I mean with all those if statements that might escalate quickly if you get some more extensive data:

function change () {
  var arrayName = ['bob', 'john']
  var arrayYear = [1997, 1995]
  var inp = document.getElementById('in')
  var index = arrayName.indexOf(inp.value)

  document.getElementById('p').innerHTML = arrayYear[index]
}

And as those arrayName elements would have to be unique, you might actually use an object literal as a dictionary instead:

function change () {
  var birthYears = {
    'bob': 1997,
    'john': 1995
  }

  var inp = document.getElementById('in')

  document.getElementById("p").innerHTML = birthYears[inp.value]
}

This way you also don’t have to take care that the lookup array is in sync with the data array.

1 Like

thank i hope i will learn alot here, one question how many post can i place on here

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.