0

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;

// ADD NEW SEARCH FIELD
$("#addNewSearchField").click(function() {
$("#Form").append(

  "<input id='AS"+index+"' type='text' name='' value=''>"+
  "<select id='SEL"+index+"' onChange='updateName2(index)'>"+
      "<?php
      foreach ($fields as $key => $value) {
        if($key=="select"){
          echo "<option selected value='".$key."'>".$value."</option>";
        }else{
          echo "<option value='".$key."'>".$value."</option>";}
        };
      ?>"
   +"</select><br>"
);
index += 1;
})
6
  • Try to console.log(e) it should be null witch explains the rest. Commented Jan 11, 2018 at 20:05
  • @NikolaAndreev yes it gives TypeError: null is not an object (evaluating 'e.options') so it does not find the object at all ? Commented Jan 11, 2018 at 20:07
  • someone posted and deleted an answer that suggested updateName2(index) should be updateName2('+index+') and I agree but I dont think that is the root of your issue. Commented Jan 11, 2018 at 20:10
  • 1
    @NappingRabbit I deleted my answer at first, since I thought I had misread the code. I've now read the code properly and have undeleted and slightly edited the answer. Commented Jan 11, 2018 at 20:12
  • so if you make that fix and comment out the lines: var valueSelect... and document.getElement... then console.log(e) what do you get? Commented Jan 11, 2018 at 20:13

1 Answer 1

1

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 + ")'>"+
Sign up to request clarification or add additional context in comments.

1 Comment

Star ! worked like a charm. For some reason I thought about it and I was sure to leave it as string. lesson learned. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.