2 回答
TA贡献1735条经验 获得超5个赞
这对我来说很好
<?php Route::add('/route', function() {
$array = [
[
'price_name' => 'Xiaomi Poco X3',
'price' => 2000
],
[
'price_name' => 'Xiaomi Poco F1 plus',
'price' => 1500
],
[
'price_name' => 'Xiaomi Poco F1',
'price' => 1000
]
];
foreach($array as $key => $value) {
?>
<div id="form">
<input type="number" id="input_value" class="colorqty" name="color[<?php echo $key; ?>][unit]" value="0" min="0" class="color_qty_1" onkeyup="updateTotal();">
<input type="text" value="<?php echo $value['price_name']; ?>" name="color[<?php echo $key; ?>][price_name]" readonly="readonly" class="color_qty_2">
<input type="text" data-id="<?php echo $key; ?>" value="<?php echo $value['price']."€"; ?>" id="price" name="xrwmas" readonly="readonly" class="color_qty_2" id="tests"> <br />
</div>
<?php
}
echo '<p>SUM <span id="sum">0</span></p>';
?>
<script>
function updateTotal(value,id) {
var elements = document.getElementsByTagName('input')
var input_val = 0;
var price_val = 0;
for(let i = 0 ; i < elements.length; i++) {
if(elements[i].getAttribute('id') == 'price') {
price_val += parseInt(elements[i].value.replace('€',''))
}
if(elements[i].getAttribute('id') == 'input_value') {
input_val += parseInt(elements[i].value)
}
}
document.getElementById('sum').innerHTML = !Number.isNaN(price_val * input_val) ? price_val * input_val : 0
}
</script>
<?php
});
?>
你只需要 javascript 就可以做到吗
TA贡献1776条经验 获得超12个赞
所以对于一开始的代码,我们在我们需要的所有项目中添加唯一的 id。在这个例子中价格和输入所以这里是例子
<?php
foreach($choice3 as $choice3){
?>
//(1)
<input type="number" class="colorqty" name="color[<?php echo $i; ?>][unit]" step="<?php echo $step; ?>" value="0" min="0" class="color_qty_1" onchange="updateSum();" id="input_value_<?php echo $i; ?>">
//(2)
<input type="text" value="<?php echo $choice3['price_name']; ?>" name="color[<?php echo $i; ?>][price_name]" readonly="readonly" class="color_qty_2">
//(3)
<input type="text" value="<?php echo $choice3['price']."€"; ?>" name="xrwmas" readonly="readonly" class="color_qty_2" id="price_<?php echo $i; ?>">
然后我们只需要按类获取一个元素并计算其长度的 JS,然后你就可以看到它适用于无限输入。
function updateSum(value,id) {
var elements = document.getElementsByClassName('colorqty').length;
var input_val = 0;
var price_val = 0;
var multipl = 0;
var output = 0;
var i = 0;
while(i < elements ) {
price_val = document.getElementById('price_'+[i]).value;
input_val = document.getElementById('input_value_'+[i]).value;
if(input_val != null){
multipl = price_val*input_val;
output += multipl ;
document.getElementById('a3').value = !Number.isNaN(output) ? output : 0
}
i ++;
}
}
添加回答
举报