[英]Javascript Quantity Validation Multiple Inputs
I'm new to programming and still learn.我是编程新手,仍在学习。 I just want to ask how to make code validation for more than one input?
我只想问如何对多个输入进行代码验证? I have data table item.
我有数据表项。 I want to run validation input for each row.
我想为每一行运行验证输入。
My Code below is only run for the first row, and cannot running in the second row.我下面的代码只在第一行运行,不能在第二行运行。
<tr>
<td><input id="stock" type="number" name="stock" value="<?php echo $row->stock; ?>" readonly></td>
<td><input id="qty" onInput="calc();" type="number" name="qty"></td>
</tr>
<script type="text/javascript">
function calc(){
var stock = document.getElementById("stock").value;
var qty = document.getElementById("qty").value;
if(qty > stock){
alert("Qty More Than Stock!");
document.getElementById("qty").value = 1;
}
}
</script>
You can use querySelectorAll
with an data-attribute
for select all inputs
then forEach
it and check the value like:您可以使用带有
data-attribute
querySelectorAll
来选择所有inputs
然后forEach
它并检查如下值:
document.querySelectorAll('input[data-check]').forEach(el => { el.addEventListener('change', () => { if (parseInt(el.value) > parseInt(el.parentElement.previousElementSibling.children[0].value)) { alert("Qty More Than Stock!"); el.value = 0; } }); });
<table> <tr> <td>Stock</td> <td>Qty</td> </tr> <tr> <td><input id="stock" type="number" name="stock" value="2" readonly></td> <td><input data-check type="number" name="qty"></td> </tr> <tr> <td><input id="stock" type="number" name="stock" value="3" readonly></td> <td><input data-check type="number" name="qty"></td> </tr> </table>
PS.附注。 Remember to use always a structure like my example else my code probably doesn't work.
请记住始终使用像我的示例一样的结构,否则我的代码可能不起作用。
in fact el.parentElement.previousElementSibling.children[0].value
it's like say: element - parent of element (td) - previous element (other td) - the first children of the previus element (input).实际上
el.parentElement.previousElementSibling.children[0].value
就像说:元素 - 元素的父元素 (td) - 前一个元素(其他 td) - 前一个元素(输入)的第一个子元素。
Another option is use another data-attribute for select the stock value like:另一种选择是使用另一个数据属性来选择股票价值,如:
document.querySelectorAll('input[data-check]').forEach(el => { el.addEventListener('change', () => { let stock = document.querySelector('input[data-index="'+el.dataset.stock+'"]'); if (parseInt(el.value) > parseInt(stock.value)) { alert("Qty More Than Stock!"); el.value = 0; } }); });
<table> <tr> <td>Stock</td> <td>Qty</td> </tr> <tr> <td><input data-index='0' type="number" name="stock" value="2" readonly></td> <td><input data-check data-stock='0' type="number" name="qty"></td> </tr> <tr> <td><input data-index='1' type="number" name="stock" value="25" readonly></td> <td><input data-check data-stock='1' type="number" name="qty"></td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.