I'm progamming a website and I would love to select all my dropdowns automatically instead of doing it manually. The thing is that my JS code brings the values, but it doesn't select any option so the box keeps like "Select an option"
HTML:
<tr> <td>Gender</td> <td> <div class="select2-container select2-container-active" id="s2id_ContentPlaceHolder1_personDetails_genderDropDownList"> <a href="javascript:void(0)" class="select2-choice select2-default" tabindex="-1"> <span class="select2-chosen" id="select2-chosen-2">Select an Option</span> <abbr class="select2-search-choice-close"></abbr> <span class="select2-arrow" role="presentation"> <b role="presentation"></b></span></a><label for="s2id_autogen2" class="select2-offscreen"></label> <input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-2" id="s2id_autogen2" tabindex="0" autocomplete="Female"></div> <select name="_ctl0:ContentPlaceHolder1:personDetails:genderDropDownList" id="ContentPlaceHolder1_personDetails_genderDropDownList" onchange="nzis.UpdateDropdownErrorLabel(this)" errorlabel="mandatory" tabindex="-1" title="" style="display: none;"> <option selected="selected" value=""></option> <option value="M">Male</option> <option value="F">Female</option> </select> </td> </tr>
JavaScript:
var index = document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList).selectedIndex; alert("value="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').value); alert("text="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[1].text); s2id_autogen1.value= document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[2].text; s2id_autogen1.checked = true; var index = document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').selectedIndex; alert("value="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').value); alert("text="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[1].text); s2id_autogen2.value= document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[2].text;
Any suggestion? :)
Thanks a lot!
You don't seem to have an element with id ContentPlaceHolder1_personDetails_titleDropDownList
so it's failing to get the element using document.getElementById
and therefore you're most likely getting the error Uncaught TypeError: Cannot read property 'selectedIndex' of null
in your console.
Edit : did you mean to use s2id_ContentPlaceHolder1_personDetails_genderDropDownList
as your selector?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.