seliboba98
seliboba98

Reputation: 99

jQuery get actual data-id from selector

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.net/s55rR/ Please help me to find a bug.

Upvotes: 0

Views: 1789

Answers (3)

Bill Criswell
Bill Criswell

Reputation: 32921

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

Upvotes: 6

krasu
krasu

Reputation: 2037

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

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

fiddle

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359816

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.

Upvotes: 4

Related Questions