Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html - how to get custom attribute of option tag in dropdown?

If I have this code:

 <select onchange="alert('?');" name="myname" class="myclass">      <option isred="-1" value="hi">click</option>  </select> 

How can I get the value '-1' from the custom attribute isred ? I don't want to use the value property. And I dont want to target the option tag by a name or id.

I want something like onchange="alert(this.getselectedoptionID.getAttribute('isred'));"

Can anyone help?

Also I don't want to use jquery.

like image 467
omega Avatar asked Aug 14 '12 17:08

omega


People also ask

How do I get custom attribute values?

To get custom attribute values with jQuery, we can use the data method. to add a div with the data-something custom attribute. We select the div with $ . And then we call data with the part of the attribute name after data- to get its value.

How can we get the selected option value of select tag in HTML?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

Which method is used to retrieve the option values from dropdown?

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

Does option tag have value attribute?

The value attribute for <option> tag in HTML is used to specify the value of the option element. Attribute Value: It contains single value value which has to be sent to the server. Example: This example illustrates the value attribute in option tag.


2 Answers

You need to figure out what the selectedIndex is, then getAttribute from that options[] Array.

<select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass">      <option isred="-1" value="hi">click</option>     <option isred="-5" value="hi">click</option> </select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

jsFiddle DEMO

As a side note:

Don't use inline javascript in your HTML. You want to separate your business logic from your UI. Create a javascript event handlers instead to handle this. (jQuery / Angular / etc)

like image 159
Mark Pieszak - Trilon.io Avatar answered Sep 27 '22 22:09

Mark Pieszak - Trilon.io


in jquery, you can just write:

$("#myname").find(':selected').attr('isred'); 
like image 29
Bernard Avatar answered Sep 27 '22 22:09

Bernard