1

I need to get "ID" of option instead of value.

Example.

<select id="industry">
<option id ="1" value="11">one</option>
<option id ="2" value="22">Two</option>
</select>

I know I can get values using the following

$("#industry").on("change",function(){
   var GetValue=$("#industry").val(); 
});

Is the any option to get Id

1 Answers1

4

You can use var GetValue=$("#industry option:selected").attr("id"); to do it.

Explaination:

  • #industry: Will look for element with id industry
  • #industry option: Will look for options under industry dropdown
  • option:selected: Will look for selected option. :selected is an attribute selector that looks for selected attribute in element

Once you have element, you can retrieve the id property from it.

$("#industry").on("change",function(){
 var GetValue=$("#industry option:selected").attr("id");
 alert(GetValue)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="industry">
<option id ="1" value="11">one</option>
<option id ="2" value="22">Two</option>
</select>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • I took the liberty to edit your answer. Please revert if not required – Rajesh Oct 07 '22 at 04:15
  • @Rajesh It's my pleasure for you to edit my answer,thanks once again – flyingfox Oct 07 '22 at 04:19
  • Being picky: `:selected` https://api.jquery.com/selected-selector/ is a jQuery extension for ` – freedomn-m Oct 07 '22 at 04:22
  • @freedomn-m Hmmm,since the OP is using `jQuery` so I posted my answer using `jQuery`,if want to pure `js` soultion,I think [html-how-to-get-custom-attribute-of-option-tag-in-dropdown](https://stackoverflow.com/questions/11957677/html-how-to-get-custom-attribute-of-option-tag-in-dropdown) will be helpful – flyingfox Oct 07 '22 at 04:26
  • @lucumt I have no issue with using jquery, not sure why you even mention pure js and tagged me. I'm highlighting the misleading description of `:selected` as *:selected is an attribute selector that looks for selected attribute in element* - which is misleading. – freedomn-m Oct 07 '22 at 04:28