Update HTML attribute from appended HTML element

User is adding a new search field (input field + select element). When user selects from select element I am trying to update the "name" value from the input element. Unfortunately the following code results in the following error at the console.log line

TypeError: null is not an object (evaluating 'document.getElementById(selectID).options')

here is the code:

function updateName2(index){

  var selectID = "SEL"+index;
  var inputID = "AS"+index;

  var e = document.getElementById(selectID);
  var valueSelect = e.options[e.selectedIndex].text;

  console.log(valueSelect); //error here

  document.getElementById(inputID).name = valueSelect;

var index = 2;

$("#addNewSearchField").click(function() {

  "<input id='AS"+index+"' type='text' name='' value=''>"+
  "<select id='SEL"+index+"' onChange='updateName2(index)'>"+
      foreach ($fields as $key => $value) {
          echo "<option selected value='".$key."'>".$value."</option>";
          echo "<option value='".$key."'>".$value."</option>";}
index += 1;

1 answer

  • answered 2018-01-11 20:08 Tulir

    When creating the select block

    "<select id='SEL"+index+"' onChange='updateName2(index)'>"+

    You use the index variable in its id, but in the function in onChange you just use index as a string, which doesn't refer to the variable correctly. This means that you're running document.getElementById("SEL" + undefined), which returns null (as such an element does not exist).

    Try this instead:

    "<select id='SEL"+index+"' onChange='updateName2(" + index + ")'>"+