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

前端 未结 7 1254
小鲜肉
小鲜肉 2020-12-08 06:54

If I have this code:

 
                        
    
提交评论

  • 2020-12-08 07:20

    Use something like this:

    document.getElementById("x").onchange = function () {
        console.log(this.options[this.selectedIndex].getAttribute("isred"));
    };
    
    0 讨论(0)
  • 2020-12-08 07:24

    in jquery, you can just write:

    $("#myname").find(':selected').attr('isred');
    
    0 讨论(0)
  • 2020-12-08 07:25

    Assuming we have a HTML markup as below:

    <form id="frm_">
        <select name="Veh">
            <option value='-1' selected='selected'>Select</option>
            <option value='0' ren='x'>xxx</option>
            <option value='1' ren='y'>yyy</option>
        </select>
    </form>
    

    The attr "ren" can be accessed like this:

    function getRep() {
        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

    0 讨论(0)
  • 2020-12-08 07:25

    you can

    $(".myclass").val(function(){alert($("option",this).attr("isred"));})
    
    0 讨论(0)
  • 2020-12-08 07:33

    //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>

    0 讨论(0)
  • 提交回复
    热议问题