Home > Enterprise >  Onchange Error: undefined (setting 'value')
Onchange Error: undefined (setting 'value')

Time:12-07

I am asking for help, I have a problem because I get this error "Uncaught TypeError: Cannot set properties of undefined (setting 'value')" on my console. I can't use document.getElementByID because my ID will change, it must be class. Could someone help me what needs to be changed in this code?

function information(ele){
 
for(var i=0; i<30; i  ){
 var address1 = document.getElementsByClassName('test2')[i];

  if( ele.value == "test4"){
    address1.value = "test5";
  } else if (ele.value == "test6"){
    address1.value = "test7";
  } else if (ele.value == "test8"){
    address1.value = "test9";
  }
}
}
<div class="form grup information">
  <lable for="dates-full.names"> Names full</lable>
  <input name="dates-full.names" list="dates-full.names" type="text"
    class="form grup test1" onchange="information(this)">
  <datalist type="text" id="dates-full.names">
    <option value="test4">
    <option value="test6">
    <option value="test8">
  </datalist>
</div>


<div class="form grup test2">
  <lable for="power-full.adress"> Adress full</lable>
  <input id="test2" name="dates-full.adress" list="dates-full.adress" type="text"
  class="form grup test2">
  <datalist type="text" id="dates-full.adress">
    <option value="test5">
    <option value="test7">
    <option value="test9">
  </datalist>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There are no 30 elements with class name 'test2'. In your for loop, you iterate over 30 possible elements, and then you search for the nth element with class name 'test2'. Yet there might be less than 30 elements. Iterating over non existent elements.

A possible solution to this would be to do a foreach instead of a for. Iterating over all the elements.

Try these: For-each over an array in JavaScript

CodePudding user response:

Try this:

function information(ele){
  var address1 = document.getElementsByClassName('test2');
  for(var i=0; i<address1.length; i  ){
    if( ele.value == "test4"){
      address1[i].value = "test5";
    } else if (ele.value == "test6"){
      address1[i].value = "test7";
    } else if (ele.value == "test8"){
      address1[i].value = "test9";
    }
  }
}
  • Related