jQuery Get Select ID Examples
Did you need to find out what the ID of a Select is using jQuery and do not know how to retrieve it? In this article, I am going to share with you a very simple way to get select dropdown ID using jQuery. Actual code is just 1 line, so it’s super easy to follow and implement.
Examples to Get Select ID using jQuery
Let’s assume that you have 2 selects with ID “city” & “state”. The HTML code would be:
<select name="city" id="city"> <option value="c1">c1</option> <option value="c2">c2</option> </select> <select name="state" id="state"> <option value="s1">s1</option> <option value="s2">s2</option> </select>
Now you want to get the ID of the select whose value has been changed. You can do it in the following manner:
Example 1 – Get Select ID on change using jQuery
<script type="text/javascript">
$(document).ready(function() {
$('select').change(function(){
var id = $(this).attr('id');
alert(id);
});
});
</script>When you run the above example, you will see the 2 selects. Simply select a different value from the list of options . As soon as you do that, you will see the JavaScript alert that shows you the ID of the select in which you just made the change.
Example 2 – Get Select ID using name attribute using jQuery
Let’s take the above example as the basis for this example. Let’s assume that you have only the name of the select and now you want to get the select ID using just the name. For illustration purposes, let’s assume that you want to get the ID of the “description” select using just it’s name. You can do it as below:
<script type="text/javascript">
$(document).ready(function() {
var id = ( $('select[name="state"]').attr('id') );
alert(id);
});
</script>In the above example, when you run the page, you will receive a JavaScript alert box that gives you the ID of the “state” select. Note that we are using the “name” attribute of the “state” select in order to get it’s ID.
Example 3 – Get Select ID using class
Let’s assume that you have applied a class of “my_select” to all the selects. You can now find out the ID of the select whose value has been changed using the class like so:
<script type="text/javascript">
$(document).ready(function() {
$('.my_select').change(function(){
var id = $(this).attr('id');
alert(id);
});
});
</script>When you run the above example, you will see the 2 input selects. Simply select a different value from the list of available options for any of the select dropdown. As soon as you do that, you will see the JavaScript alert that shows you the ID of the select in which you just made the change.
That’s it!
Do you know of any other ways to get select ID using jQuery? Feel free to suggest by commenting below.