Skip to content Skip to sidebar Skip to footer

Html - How To Get Custom Attribute Of Option Tag In Dropdown?

If I have this code: How can I

Solution 1:

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)

Solution 2:

in jquery, you can just write:

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

Solution 3:

Use something like this:

document.getElementById("x").onchange = function () {
    console.log(this.options[this.selectedIndex].getAttribute("isred"));
};

Solution 4:

Assuming we have a HTML markup as below:

<formid="frm_"><selectname="Veh"><optionvalue='-1'selected='selected'>Select</option><optionvalue='0'ren='x'>xxx</option><optionvalue='1'ren='y'>yyy</option></select></form>

The attr "ren" can be accessed like this:

functiongetRep() {
    var ren = document.forms['frm_'].elements['Veh'].options[document.forms['frm_']
                 .elements['Veh'].selectedIndex].getAttribute('ren');
    console.log("Val of ren " + ren); //x or y
}

Demo

Solution 5:

//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)
}
<selectid="name_your_id"name="myname"class="myclass"><optionisred="423423"value="hi">One</option><optionisred="-1"value="hi">Two</option></select>

Post a Comment for "Html - How To Get Custom Attribute Of Option Tag In Dropdown?"