skip to Main Content

I have the following select box.

I have the following select box
 <select name="model_number"  class="iump-form-select "   ><option value="ZL111" >ZL111</option><option value="ZL222" >ZL222</option><option value="ZL333" >ZL333</option><option value="ZL444" >ZL444</option><option value="ZL555" >ZL555</option></select>

before entering this page I am setting a cookie with the value for the model number, eg "ZL222"

 var M111 = getCookie("ModelNumber");

when this page loads I would like the appropriate model number already selected based on the value of the input cookie.

I want the select box to "auto change" to the value read from the cookie. I can read the cookie just fine, but I don’t know how to set the select box to the correct choice. For example, if the cookie is ZL222 when the page finishes loading i want the select box to show ZL222 as the SELECTED value.

<option value="ZL222" >ZL222</option>

However, I am stuck on how to do the above.

I tried this based on other examples I saw, but it doesn’t work:

document.getElementById('model_number').getElementsByTagName('option')[M111].selected = 'selected';

I want to be able to preselect the value based on the incoming cookie value, in this case, which is set to a variable called M111.

3

Answers


  1. You cannot use getElementById() because your selection menu doesn’t have an ID but a NAME!

    If this selection menu is not a part of a form to necessitate a NAME then change that to ID like this…

    <select id="model_number">
    

    And then to set the selected index use this method…

    model_number.selectedIndex=3;  // or whatever number
    

    If it’s part of a FORM and thus want to preserve the NAME, you can access it like this:

    Given…

    <form name="TheForm">
    

    Then…

    document.TheForm.model_number.selectedIndex=3; 
    

    Alternatively you can also access it like this:

    document.TheForm.elements['model_number'].selectedIndex=3;
    
    Login or Signup to reply.
  2. Select the input, set the value, fire the change event

    const sel = document.getElementById('model_number')
    sel.value = getCookie("ModelNumber");
    sel.dispatchEvent(new Event("change"));
    
    Login or Signup to reply.
  3. I hate doing unorthodox things but here goes anyway…

    var M=document.TheForm.model_number;
    
    var E=M.getElementsByTagName('option');
    
    for(var i=0; i<E.length; i++){
    
     if(E[i].value==M111){M.selectedIndex=i; break;}
    
    }
    

    PS: Change the form name to what you’ve got.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search