How to get Dropdown id in JQuery?

Answered

Please share your views about this question…

Hafiz Farhan Junior Programmer Asked on November 26, 2015 in Interview Questions.
Add Comment
1 Answer(s)
Best answer

i don’t clear what you really want to ask . I guess you are asking about the selected item ID of drop down through jQuery ? If yes , Here is the solution you can implement to get selected Item ID of Dropdown in jQuery .

HTML Test Markup : 


Example : 1
<Select id = "example1">
<option value = "1">C++</option>
<option value = "2">JAVA</option>
<option value = "3">C#</option>
<option value = "4">PHP</option>
Example 2 :
<Select id = "example2">
<option id = "1">C++</option>
<option id = "2">JAVA</option>
<option id = "3">C#</option>
<option id = "4">PHP</option>

jQuery Code : 

// On Change event
$("#example1").on('change' , function () {
     
         alert($(this).val());
});
$("#example2").on('change' , function () {
       alert($(this).find('option:selected').attr('id'));
});

Note: In DropdownList, if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id attribute inside option .Its not standard paractise though i did both in my answer but i prefer example 1 .

Hope this answer will help you .

Salman Nazir Junior Programmer Answered on November 27, 2015.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.