javascripthtmlindexingdrop-down-menuselectedindex

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


Solution

  • 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 i.e. value="1") Then you can just use select.checkValidity(), which returns true or false.