0

I have the following JavaScript/jQuery:

$select.append($("<option />")
    .val(this.id)
    .text(this.text)
    .data('name', this.name)
    .data('isstorage', this.isstorage));

It correctly sets the <option> tag's value and text values. But it doesn't set the data-name or data-isstorage attributes.

Can someone tell me what I have wrong here?

Full example:

var $select = $('#myselect');

var x = {
  id: 'id',
  text: 'text',
  name: 'name',
  isstorage: 'isstorage'
};

$select.append($("<option />")
    .val(x.id)
    .text(x.text)
    .data('name', x.name)
    .data('isstorage', x.isstorage));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <select id="myselect" />
</div>
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Can you make this into a [mcve]? – SuperStormer Sep 30 '22 at 22:47
  • 2
    .data isn't for setting attributes, it's for setting the dataset properties. If you want to actually see the attributes, use `.attr('data-name', this.name);` – Robert McKee Sep 30 '22 at 22:52
  • @RobertMcKee: I find this confusing. `$el.data('name')` returns the value of the `data-name` attribute. You're saying `$el.data('name', 'abc')` doesn't set it? – Jonathan Wood Sep 30 '22 at 22:55
  • Yes, it does not set an attribute. What actually happens is the data-* attributes are consumed and loaded into the element's dataset property. Jquery will read/set the values there, but it's a one-way ticket, the set values don't go back to data-* attributes. The content IS there though.. add `console.log($('#myselect option:first').data('name'))` to the bottom of your code pen, and you will see in the console it outputs name. – Robert McKee Sep 30 '22 at 23:00

1 Answers1

0

Try

.attr('data-name', this.name)
.attr('data-isstorage', this.isstorage)); 

.data() is for parsing not setting content

noremacsim
  • 59
  • 4