Introduction with JQUERY - Manipulating Dropdowns using JQUERY

Guest Posts Paolo Nikko Nuñal

One of the most common problems I often find in many programming forums is getting the value of a selected option in a drop down. Well, in JQUERY you can select it easily with just a couple of lines. Getting the selected value's in a drop down is important mostly used in forms in getting the users selection. In this tutorial you can see how it is easily done.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here





Select elements typically have two values that you want to access, the first value is the one that you are actually sending to the server.

Code


$("#selection").val();


From the code above, we are just getting the value of the HTML element with the "ID" #selection.

Code


<select id="dropdown">
   <option value="1">John</option>
   <option value="2">Drake</option>
   <option value="3">Simon</option>
   <option value="4">Bob</option>
</select>


If ever you want to get the value of what is being selected on the drop down. All you have to do use the "option:selected".

Code


$("#dropdown option:selected").text();


By using the .text() method, you are actually getting the names of the selected item in the drop down. If you select the first option, then you will be return with the text "John". However, if you want to get the value all you have to do is change the .text() method into a .val() method.

Code


$("#dropdown option:selected").val();


In that case, if you select "Drake" from the dropdown list, you are returned with the value "2".

Code


var dropdownValue = $("#dropdown option:selected").val();


The variable dropdownValue will store what is being selected on the dropdown.
For more information you can check out Dr. Richard's tutorial.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here