6

我正在尝试将选择框选项上的自定义数据属性发布到隐藏的表单字段。

这是我的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>

和 jQuery

$('#submit_btn').click(function() {
  var options = $('select#sampleorder');    
  var samplesSelected = options.val();

  $('input[name=order]').val(samplesSelected);
  $('input[name=quantity]').val(sampleAmount);
});  

我猜我的变量“sampleAmount”应该看起来像这样

  var sampleAmount = options.val().data("amount");

但这并没有给我预期的结果。获取每个项目的数据属性值的好方法是什么?

谢谢!

4

6 回答 6

16

为什么使用 jQuery?只需使用event.target.options[event.target.selectedIndex].dataset.amount

于 2014-04-17T00:55:16.287 回答
3

尝试这个:

$('#submit_btn').click(function() {
  var samplesSelected = $('#sampleorder').val(),
      sampleAmount = $('#sampleorder option:selected').data("amount");
  $('input[name=order]').val(samplesSelected);
  $('input[name=quantity]').val(sampleAmount);
});
于 2013-06-11T08:38:51.343 回答
2

尝试这个,

HTML

将 id 属性添加到您的select drop down 喜欢

<select id="sampleorder" >
   ....

脚本

 var sampleAmount = $('select#sampleorder option:selected').data("amount");

小提琴 http://fiddle.jshell.net/3gCKH/

于 2013-06-11T08:38:07.903 回答
2

在纯香草 javascript 中,您可以使用:

var sampleAmount = this.selectedOptions[0].getAttribute('data-amount'));

例子:

function SelectChange(event) {
    console.log(event.selectedOptions[0].getAttribute('data-amount')); 
}
<select onchange="SelectChange(this)">
    <option data-amount="1">one</option>
    <option data-amount="2">two</option>
    <option data-amount="3">three</option>
</select>

于 2018-08-21T02:04:40.890 回答
1

另一个香草 JS 答案:

var selectContainer = document.getElementById('sampleorder')
var selectedOption  = selectContainer.selectedOptions.item()
var amount          = selectedOption.getAttribute('data-amount')
于 2016-11-16T21:36:00.743 回答
0

我忘了提到它必须是一个多选框,对不起。在您的帮助和对 jQuery 文档的简要介绍下,我设法解决了这个问题:

$("select#sampleorderm").change(function () {
    var samplesSelected = options.val().join("::");
    var samplesAmount = "";
        $("select#sampleorderm option:selected").each(function () {
            samplesAmount += $(this).data("amount") + " ";
        });

    $('input[name=sampleorder]').val(samplesSelected);
    $('input[name=sampleorderquantity]').val(samplesAmount);
 });
于 2013-06-11T09:07:41.433 回答