简体   繁体   中英

How to get ID of select when user selected option?

I have 2 select option. Now I want to get id of select when user selected option. Ex: If I selected Option1 then alert id="my_select1" and if I selected MyOption2 then alert id="my_select2" . How can I do that?

<select id="my_select1">
  <option value="o1" id="id1">Option1</option>
  <option value="o2" id="id2">Option2</option>
</select>

<select id="my_select2">
  <option value="mo1" id="mid1">MyOption1</option>
  <option value="mo2" id="mid2">MyOption2</option>
</select>

 $('select').change(function() { alert($(this).attr('id'))//use attr() to get id }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="my_select1"> <option value="o1" id="id1">Option1</option> <option value="o2" id="id2">Option2</option> </select> <select id="my_select2"> <option value="mo1" id="mid1">MyOption1</option> <option value="mo2" id="mid2">MyOption2</option> </select> 

  1. Use .attr() to get id
  2. Use $(this) to get the id of the select that made the change

Bind a change event handler and use this.id to get id of the event fired select tag. Although you can use $(this).attr('id') to get the id attribute value.

 $('#my_select1,#my_select2').change(function() { alert(this.id) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="my_select1"> <option value="o1" id="id1">Option1</option> <option value="o2" id="id2">Option2</option> </select> <select id="my_select2"> <option value="mo1" id="mid1">MyOption1</option> <option value="mo2" id="mid2">MyOption2</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM