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

Viewed 109185

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.

7 Answers

in jquery, you can just write:

$("#myname").find(':selected').attr('isred');

//Pure Javascript solution, and elegant one check if you really want to leverage the power of javascript.

// Listening to a onchange event by ID attached with the select tag.
document.getElementById("name_your_id").onchange = function(event) {

//event.target.selectedOptions[0] have that option. as this is single selection by dropdown. this will always be 0th index :) 
let get_val = event.target.selectedOptions[0].getAttribute("isred");
console.log("Value from the Attribute: ", get_val)
}
 <select id="name_your_id" name="myname" class="myclass">
    <option isred="423423" value="hi">One</option>
    <option isred="-1" value="hi">Two</option>
 </select>

Related