我有2个输入字段:
<div class="row">
<div class="col-1-2"><input type="text" placeholder="Item 1" name="custom_item_1" id="custom-item-1"></div>
<div class="col-1-2"><input type="number" placeholder="Amount 1" name="custom_amount_1" id="custom-amount-1"></div>
</div>
它们不是必需的,但如果有一个数据,那么我需要它们都填写...
当填写一个输入时,最好的方法是在两个输入的末尾添加一个必需的吗?
请记住,我已经在使用JS来动态添加更多行,使用Item / Amount 2,3,4等...
我不知道该怎么做。
我认为工作流程会是这样的:
1)填写后,找到'item'和'amount'的ID - 例如... custom-item-1和custom-amount-1
2)在id为
的输入中添加'required'这是我用来动态添加行的代码,它很有用:
// add custom fields - add fields upon pressing button
var iCustom = 2; // starts at 2 because 1 is already present
function addCustomFields() {
var newRow = document.createElement('div');
newRow.className = 'row';
newRow.innerHTML = '<div class="col-1-2"><input type="text" placeholder="Item ' + iCustom + '" name="custom_item_' + iCustom + '" id="custom-item-' + iCustom + '"></div><div class="col-1-2"><input type="number" placeholder="Amount ' + iCustom + '" name="custom_amount_' + iCustom + '" id="custom-amount-' + iCustom + '"></div>';
document.getElementById('section-add-custom-fields').appendChild(newRow);
iCustom++;
}
document.getElementById('add-custom-fields').addEventListener('click', addCustomFields);
编辑:
最终代码:
// requires both inputs to be filled
document.getElementById('form-button-submit').addEventListener('click', function() {
for (var i = 1; !!document.getElementById("custom-item-"+i); i++) {
var itemEntered = !!document.getElementById("custom-item-"+i).value,
amountEntered = !!document.getElementById("custom-amount-"+i).value;
if(itemEntered != amountEntered) {
document.getElementById("custom-item-"+i).required = true
document.getElementById("custom-amount-"+i).required = true
}
}
});
<button type="submit" id="form-button-submit">Continue</button>
答案 0 :(得分:2)
我只是将此验证代码放在您拥有的任何提交按钮的事件监听器中:
for(var i = 1; !!document.getElementById("custom-item-"+i); i++) {
var itemEntered = !!document.getElementById("custom-item-"+i).value,
amountEntered = !!document.getElementById("custom-amount-"+i).value;
if(itemEntered != amountEntered) {
// One was entered, but both weren't filled out
// so handle that situation accordingly
}
}
一些解释:!!
turns stuff into boolean values。因此,for循环基本上遍历所有“自定义项”字段,直到找到不存在的字段为止。
有关如何处理if语句中的错误情况的一些选项: