jQuery - getting custom attribute from selected option

后端 未结 12 1201
礼貌的吻别
礼貌的吻别 2020-11-30 17:19

Given the following:


                        
    
提交评论

  • 2020-11-30 17:44

    Simpler syntax if one form.

    var option = $('option:selected').attr('mytag')

    ... if more than one form.

    var option = $('select#myform option:selected').attr('mytag')

    0 讨论(0)
  • 2020-11-30 17:44

    You can also try this one as well with data-myTag

    <select id="location">
        <option value="a" data-myTag="123">My option</option>
        <option value="b" data-myTag="456">My other option</option>
    </select>
    
    <input type="hidden" id="setMyTag" />
    
    <script>
        $(function() {
            $("#location").change(function(){
               var myTag = $('option:selected', this).data("myTag");
    
               $('#setMyTag').val(myTag);
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-30 17:45

    Try this:

    $("#location").change(function(){
                var element = $("option:selected", this);
                var myTag = element.attr("myTag");
    
                $('#setMyTag').val(myTag);
            });
    

    In the callback function for change(), this refers to the select, not to the selected option.

    0 讨论(0)
  • 2020-11-30 17:48

    The easiest one,

    $('#location').find('option:selected').attr('myTag');
    
    0 讨论(0)
  • 2020-11-30 17:50

    You're pretty close:

    var myTag = $(':selected', element).attr("myTag");
    
    0 讨论(0)
  • 提交回复
    热议问题