Joh*_*jff 3 javascript forms jquery
我正在尝试将选择框选项上的自定义数据属性发布到隐藏的表单字段.
这是我的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>
Run Code Online (Sandbox Code Playgroud)
和jQuery
$('#submit_btn').click(function() {
var options = $('select#sampleorder');
var samplesSelected = options.val();
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
Run Code Online (Sandbox Code Playgroud)
我猜我的变量"sampleAmount"应该看起来像这样
var sampleAmount = options.val().data("amount");
Run Code Online (Sandbox Code Playgroud)
但它没有给我预期的结果.获取每个项目的数据属性值的好方法是什么?
谢谢!
zac*_*ify 13
为什么要用jQuery?只是用event.target.options[event.target.selectedIndex].dataset.amount
尝试这个:
$('#submit_btn').click(function() {
var samplesSelected = $('#sampleorder').val(),
sampleAmount = $('#sampleorder option:selected').data("amount");
$('input[name=order]').val(samplesSelected);
$('input[name=quantity]').val(sampleAmount);
});
Run Code Online (Sandbox Code Playgroud)