dardy
dardy

Reputation: 433

Set data of the first option in a drop-down list

I have this option:

<select id="options">
   <option val="n_0" data-option-code="code_0">option 0</option>
   <!-- ... -->
</seclect>

When I do:

$("#options option:first").data('option-code', 'new-value');

It seems that nothing happens. I mean, I always have the same data-option-code="code_0". What am I doing wrong?

Upvotes: 2

Views: 84

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The data() setter method adds information to jQuery's internal cache. It does not affect the DOM. If you use the getter of data() you'll see the information has been stored correctly, eg:

var foo = $("#options option:first").data('option-code'); // = 'new-value'

If you require the data attribute to be updated in the DOM, use attr():

$("#options option:first").attr('data-option-code', 'new-value');

Upvotes: 3

Related Questions