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
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…
And then to set the selected index use this method…
If it’s part of a FORM and thus want to preserve the NAME, you can access it like this:
Given…
Then…
Alternatively you can also access it like this:
Select the input, set the value, fire the change event
I hate doing unorthodox things but here goes anyway…
PS: Change the form name to what you’ve got.