简体   繁体   中英

Determine the Selected Index number of a drop down menu?

I'm trying to make sure that the user is not selecting the default of a drop down method by determining the index number selected. It seems to be only returning false even though I believe the code is correct... So far I have the code listed below but its not working, any ideas?

 <p id="Gender"> <label for="Gender">Gender: </label> <select required> <option disabled selected value="Select">Select</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> </p>

 function validate1() { valCheck3 = true; var dropD1 = document.getElementById("Gender"); var resultSelect = dropDown1(dropD1); var image3 = getImage(Boolean(resultSelect), "gender"); var labelGender = getNotification3(Boolean(resultSelect), "gender"); document.getElementById("Gender").appendChild(image3); document.getElementById("Gender").appendChild(labelGender); } function dropDown1(select){ if(select.selectedIndex > 0){ return true; } valCheck3 = false; return false; }

EDIT: I added the HTML I used the setting to make the answer required, the problem is I need to have a button that checks whether the answer has been selected to insert an image next to the box. So in this case I figured I could determine the selected index number of the drop down so that I could determin

You can add the required attribute to the select element, then add some value attribute to each option except for the first one (use value without the value itself ie value="1") Then you can just use select.checkValidity(), which returns true or false.

I'm trying to make sure that the user is not selecting the default of a drop down

You can just add disabled attribute to the <option> and also make it default. If the user opens the dropdown, the default option can not be clicked anymore and the user has to choose an onther option.

Example:

 <form action=""> <select required> <option disabled selected value>Default option</option> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <input type="submit"> </form>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM