Search code examples
javascriptjqueryselectselectors-api

How to select the <select> tag including checked and unchecked options using queryselectorAll()?


//initial  code   

var selectInputs = document.querySelectorAll('option:checked');
    var selectArray=[];                        
      for(var i=0;i<selectInputs.length;i++)
          {
            selectArray[i]=selectInputs[i].value;//am doing this since I found out (from stackoverflow) that selectInputs contains a NodeList and in order to use it, it must be converted or saved as an array
          }

     //later stage manipulation code

var input_select=  document.querySelectorAll('option:checked');
for(var i=0;i<input_select.length;i++)
{
input_select[i].value=selectArray[i];//I am trying to change the value of the <select> option
}

PURPOSE: User selects option in a form and data is saved in local storage. I want to reflect the same when the form reloads. I am not working for a specific form so using Jquery seems futile(as it works with class or id and I don't know the id or class of any tag of the generic form)

PROBLEM: The problem is that I wanna select the entire options set of tag and not just the ones that have been checked/selected.The code above sets the value of the default selected option to the one stored in local storage but doesn't reflect the change in the form. It always displays the default value though giving

alert(input_select[i].value);

reflects the internal change perfectly!


Solution

  • Guess I gotta answer my own question :-D

    If you could see, there's just one silly change in the

    //later stage manipulation code ABOVE.

    ANSWER:

    var input_select=  document.querySelectorAll('select');
    for(var i=0;i<input_select.length;i++)
    {
    input_select[i].value=selectArray[i];//I am trying to change the value of the <select> option
    }
    

    Instead of

    var input_select=  document.querySelectorAll('option:checked');
    

    It must be

    var input_select=  document.querySelectorAll('select');
    

    REASON: I have been trying to assign the stored value into the option itself (the option tag) rather than the select tag as a whole.

    WARNING: In the code

    input_select[i].value=selectArray[i];
    

    It could also be

    input_select[i].value="Friday";
    

    provided that you already have an option like that, else it would show a blank.

    <select name="days" id=days">
    <option value="0"> Friday </option>
    <option value="1"> Monday </option>
    </select>
    
    works
    
    <select name="days" id=days">
    <option value="0"> Saturday </option>
    <option value="1"> Monday </option>
    </select>
    
    doesn't work. Shows a blank.