I'm trying to post a custom data attribute on a select box option to a hidden form field.
Here's my html:
<select id="sampleorder" multiple="multiple">
<option value='xxx' data-amount='5'>Name</OPTION>
<option value='xxx' data-amount='15'>Name</OPTION>
<option value='xxx' data-amount='2'>Name</OPTION>
</select>
And jQuery
$('#submit_btn').click(function() {
var options = $('select#sampleorder');
var samplesSelected = options.val();
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
I'm guessing that my variable "sampleAmount" should look somewhat like this
var sampleAmount = options.val().data("amount");
But it's not giving me the expected results. What would be a good approach to get the data attribute value per item?
Thanks!
HTML <option> data-* Attribute A data-* attribute on an <option> tag attaches additional data to the option item. To create a custom attribute, replace * with a lowercase string, such as data-id , data-status , or data-location .
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
why use jQuery? Just use event.target.options[event.target.selectedIndex].dataset.amount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With