javascript - jQuery get actual data-id from selector - Stack Overflow

I havea selector on webpagewith data-id and valueHTML<select id="s1"><option dat

I have a selector on webpage with data-id and value

HTML

    <select id="s1">
        <option data-id="01">aaaa1</option>
        <option data-id="23">bbb1</option>
        <option data-id="451">ccc1</option>
        <option data-id="56">ddd1</option>

    </select>

<p></p>

JAVASCRIPT

$('#s1').change(function() { 
       var val = $(this).val();   
       var val_id =$(this).find('option').data('id');
       $("p").html("value = " + val + "<br>" +"value-data-id = "+  val_id);
});

I wanna have actual value from selected selector and his data-id. I do not understand why I have data-id from only first option. This is my code / Please help me to find a bug.

I have a selector on webpage with data-id and value

HTML

    <select id="s1">
        <option data-id="01">aaaa1</option>
        <option data-id="23">bbb1</option>
        <option data-id="451">ccc1</option>
        <option data-id="56">ddd1</option>

    </select>

<p></p>

JAVASCRIPT

$('#s1').change(function() { 
       var val = $(this).val();   
       var val_id =$(this).find('option').data('id');
       $("p").html("value = " + val + "<br>" +"value-data-id = "+  val_id);
});

I wanna have actual value from selected selector and his data-id. I do not understand why I have data-id from only first option. This is my code http://jsfiddle/s55rR/ Please help me to find a bug.

Share Improve this question edited Oct 25, 2013 at 18:59 messivanio 2,31118 silver badges25 bronze badges asked Oct 25, 2013 at 18:35 seliboba98seliboba98 991 gold badge2 silver badges8 bronze badges 1
  • did you try with a more conservative .attr("data-id")? – leonard vertighel Commented Oct 25, 2013 at 18:38
Add a ment  | 

3 Answers 3

Reset to default 6

You can do $(this).find('option:selected').data('id').

You've selected multiple elements ($(this).find('option')) but .data() only returns the value from the first element if called on a jQuery with length >1:

Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

If you only want the data-id value from the user-selected<option>, then you need to select only that element.

Because you selecting all options, and jQuery returning .data('id') of first one

var val_id =$(this).find('option:selected').data('id');

fiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744068056a4553028.html

相关推荐

  • javascript - jQuery get actual data-id from selector - Stack Overflow

    I havea selector on webpagewith data-id and valueHTML<select id="s1"><option dat

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信