gpt4 book ai didi

javascript - 根据所选产品从数据数组填充价格

转载 作者:行者123 更新时间:2023-12-02 19:12:31 24 4
gpt4 key购买 nike

我有一个 json 数组

var data = [ { "id": "1", "label": 1, "value": "11.00" }, 
{ "id": "2", "label": 2, "value": "21.00" },
{ "id": "3", "label": 3, "value": "31.00" },
{ "id": "4", "label": 4, "value": "40.00" },
{ "id": "5", "label": 5, "value": "50.00" },
{ "id": "6", "label": 6, "value": "60.00" },
{ "id": "9", "label": 9, "value": "90.00" },
{ "id": "8", "label": 8, "value": "80.00" },
{ "id": "7", "label": 7, "value": "70.00" }
];

和一个来自

<form action="" method="POST">
Quantity1: <input type="text" name="quantity1" id="quantity1">
Product1: <select name="product1" id="product1"><option value="1">Product 1</option><option value="2">Product 2</option></select>
Price1: <input type="text" name="price1" id="price">
Quantity2: <input type="text" name="quantity2" id="quantity2">
Product2: <select name="product1" id="product2"><option value="1">Product 1</option><option value="2">Product 2</option></select>
Price2: <input type="text" name="price2" id="price">
.
.
.
<input type="submit" value="submit">
</form>

我想自动填充产品的价格。很抱歉我不太了解 jquery 和 javascript。尝试过但没有成功

$( "#product1" ).change(function(){
source: data,
minLength: 1,
select: function( event, ui ) {
$('#price1').val( ui.item.value );
}
});

请帮助我如何填充产品 1 的价格 1 和产品 2 的价格 2。

<小时/>

这是适用于 #product1 的代码

$('#product1').change(function() {  
$('input[name="unit_price1"]').val(data[$(this).val()-1].value)
});

但是一旦我尝试循环,我的循环就不可能有问题。

$(function() {
var data = <?php echo $projects; ?>;
var nbProducts = data.length;
for(var iProduct = 0; iProduct < nbProducts; iProduct++) {
$('#product'+iProduct).change(function() {
$('input[name="unit_price'+iProduct+'"]').val(data[$(this).val()-1].value)
});
}


});

最佳答案

var data = [ { "id": "1", "label": 1, "value": "11.00" }, 
{ "id": "2", "label": 2, "value": "21.00" },
{ "id": "3", "label": 3, "value": "31.00" },
{ "id": "4", "label": 4, "value": "40.00" },
{ "id": "5", "label": 5, "value": "50.00" },
{ "id": "6", "label": 6, "value": "60.00" },
{ "id": "9", "label": 9, "value": "90.00" },
{ "id": "8", "label": 8, "value": "80.00" },
{ "id": "7", "label": 7, "value": "70.00" }
];

for(var i=0; i<data.length; i++) {
$('#product1').append('<option value="' + data[i].value + '">' + data[i].label+ '</option>');
$('#product2').append('<option value="' + data[i].value + '">' + data[i].label+ '</option>');
}

$('#product1').change(function() {
$('input[name="price1"]').val($(this).val())
});

$('#product2').change(function() {
$('input[name="price2"]').val($(this).val())
});

也许您会做出这个决定。示例:http://jsfiddle.net/YvZ9v/

关于javascript - 根据所选产品从数据数组填充价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13527176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com