Monday, March 7, 2011

Get the selected item in a drop down dynamically

Actually I forgot to add this topic. I think this is the topic to discuss first. Anyway this post will tell you how to get the selected item, the selected value in a set of options of a select input field of an HTML form. The value is accessed or retrieved using java script or jquery API. The code is below.

java script code : 

document.getElementById("SELECT_ID").value;

jquery code :

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

For eg:-
If the HTML code is as below then the code will be as explained below,

<select name="sel_name" id="sel_id">
<option value="I will help you">I will help you</option>
<option value="I will not help you">I will not help you</option>
<option value="I can assist you">I can assist you</option>
<option value="I cant assist you">I cant assist you</option>
</select>

Then the java script code to dynamically pick the selected option is,


document.getElementById("sel_id").value;

and the jquery code for the same is,

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

No comments:

Post a Comment