Introduction to JQUERY - Checking Selected Dropdowns with the :selected Selector

Guest Posts Paolo Nikko Nuñal

Sometimes in developing websites we deal with checking forms. This ranges from input boxes, checkboxes, dropdown, and radio boxes just to name a few. Getting the value's of input boxes are easy with JQUERY, and so is getting the values with other form elements. In this tutorial, we are going to deal with knowing if the specific drop down is being selected with the use of the JQUERY :selected selector.

Syntax:

$(":selected")

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $(":selected").css("background-color","yellow");
});
</script>
</head>
<body>
<form>
Cellphones:
<select>
   <option>Nokia</option>
   <option>Nokia</option>
   <option>Nokia</option>
   <option selected="selected">Apple</option>
</select>
</form>
</body>
</html>


When you click on the drop-down, you will see that the "Apple" option is colored in Yellow, which indicates that it is being selected with the use of the selected attribute that we placed on the HTML option. As a word of caution, the selected selector will only work for <option> elements. It will not work for checkboxes or radio inputs.

However, we do have the checked: selector which I will be covering on the next tutorial from here on in. Stay tune.