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.
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.
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).
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.
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.
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
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)
in jquery, you can just write:
$("#myname").find(':selected').attr('isred');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With