我有一个序列化的select html元素。我需要序列化值,data-price属性以及选项文本。该脚本正在运行,但我将一个对象推到阵列上太多了。
jsfiddle:https://jsfiddle.net/kh3k7ame/3/
<form id="order">
<select name="selectProduct" id="selectProduct">
<option selected disabled hidden style="display:none;" value=""></option>
<option data-price="1.50" value="16">Product1</option>
<option data-price="0.50" value="17">Product2</option>
<option data-price="0.50" value="18">Product3</option>
<option data-price="0.30" value="19">Product4</option>
<option data-price="0.30" value="20">Product5</option>
</select>
<button type="button" name="send" id="send">Send</button>
</form>
<pre id="result"></pre>
JS:
var orderTotal = [];
$('#send').on('click', function(){
var orderData = $('form').serializeArray();
var orderValue = {};
$(orderData).each(function(i, field){
orderValue[field.name] = {value:field.value, text:$("#selectProduct option:selected").text(), price:$("#selectProduct option:selected").attr('data-price')};
});
orderTotal.push(orderValue);
console.log(orderTotal);
$('#result').html(JSON.stringify(orderTotal,null,4));
});
答案 0 :(得分:0)
如果select是单个select,我认为你可以将值保存在对象而不是数组中。
https://jsfiddle.net/kh3k7ame/4/
$('#send').on('click', function(){
var orderData = $('form').serializeArray();
var orderValue = {};
$(orderData).each(function(i, field){
orderValue[field.name] = {value:field.value, text:$("#selectProduct option:selected").text(), price:$("#selectProduct option:selected").attr('data-price')};
});
$('#result').html(JSON.stringify(orderValue,null,4));
});