Jaap Scholten Jaap Scholten - 24 days ago 10
Javascript Question

Get data attribute for selected dropdown options

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!

Answer

Try this:

$('#submit_btn').click(function() {
  var samplesSelected = $('#sampleorder').val(),
      sampleAmount = $('#sampleorder option:selected').data("amount");
  $('input[name=order]').val(samplesSelected);
  $('input[name=quantity]').val(sampleAmount);
});