Reputation: 1035
I'm still learning of how to use jQuery but I stumbled with a block and can't get through it. How to append an option
to a select
with data-*
attribute? Currently I'm appending option through this code below:
$('<option>').val(object.val).text(object.object.text).appendTo('#includedItems');
Is there a way to also add data-*
to the options?
Upvotes: 3
Views: 13626
Reputation: 977
You can use:
$('#dropdownId').append($('<option/>', {
value: value,
text: displayText,
selected: isSelected ? true : false,
'data-description': descriptionText
}));
Upvotes: 2
Reputation: 20636
Use this .attr(),
$('<option>').attr('data-name','abcd');
Or .data()
$('<option>').data('name','abcd');
$('<option>').val(object.val).attr('data-name','abcd').text(object.object.text).appendTo('#includedItems');
Note: .data()
stores data in DOM object, NOT as Html attribute while .attr()
does.
Upvotes: 7
Reputation: 2806
You can use .attr("data-lala",val)
to create an attribute on an element, or .data("lala",val)
if you dont mind if that information stays hidden in the DOM (an inspect may not show the right value).
Upvotes: 1
Reputation: 64526
Just add a attr()
or data()
call to the chain:
use attr()
if you want to have an actual data-*
attribute:
$('<option>').val(object.val).text(object.object.text).attr('data-x', 'y').appendTo('#includedItems');
^ call attr()
Use data()
to use jQuery's internal data storage system (doesn't use an attribute)
$('<option>').val(object.val).text(object.object.text).data('x', 'y').appendTo('#includedItems');
^ call data()
Upvotes: 5
Reputation: 82241
You can use:
$('<option data-smdata="value"></option>').val(object.val).text(object.object.text).appendTo('#includedItems');
Upvotes: 2