Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 321
Johan Cruijff Avatar asked Jun 11 '13 08:06

Johan Cruijff


People also ask

How add data attribute to select option?

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 .

How do you get the value of a data attribute?

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.


1 Answers

why use jQuery? Just use event.target.options[event.target.selectedIndex].dataset.amount

like image 80
zackify Avatar answered Oct 30 '22 09:10

zackify