How to Get the ID Value in a Drop Down Using jQuery
Getting the value of the ID for a drop-down box on a Web page requires the use of the "attr()" function when programming in jQuery. This function will get the value of any HTML tag attribute. You need to run this function on the "<select>" tag since that is the tag that creates drop-down boxes in HTML. Once you get the value of the ID you can output it to a part of your Web page to show to the user or see the result during your testing phases.
Instructions
-
-
1
Open your Web page in Notepad or a code editor and check that your page includes a reference to the jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
Add the above code if you do not find the reference.
-
2
Place a new pair of "<script>" tags under the jQuery reference. Write a function to check if the page finished loading between the "<script>" tags. Your jQuery script will go inside that function:
<script type="text/javascript">
$(function() {
});
</script>
-
-
3
Locate the "Submit" button code for the form in your Web page that contains the drop-down box:
<input type="submit" value="Get ID" id="getvalue" />
Add an ID attribute to the button code if it does not yet contain one.
-
4
Return to your script and add a function that will run when the user clicks on the button:
$(function() {
$("#getvalue").click(function () {
});
});
This script selects the button by its ID name, so change "getvalue" with the ID name from the "Submit" button code.
-
5
Declare a variable inside the function triggered by the click event. Make the variable equal to the ID found inside the "<select>" tag found in the form. This code will give you the ID value of the drop-down box:
var value = $("select").attr("id");
The "attr()" function in jQuery gives you the value of any HTML tag attribute, so using "id" inside the function will get you the ID value. This script uses "select" to select by the "<select>" tag that creates drop-down boxes in HTML.
-
6
Output the variable to any part of your Web page. For example, you can create a div on the page and give it an ID name of "results." The code to output to "<div id='results'>" is:
$("#results").text(idvalue);
In this code, "idvalue" is the name of the variable you created to store the ID value, and it does not need quotes.
-
7
Add "return false;" to the end of the function to keep the form from submitting any data or forwarding the user to a new Web page. The final script looks like this:
$(function() {
$("#getvalue").click(function () {
var value = $("select").attr("id");
$("#results").text(value);
return false;
});
});
-
1