I have 2 input fields:
<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>
They are not required, but if there is data in one then I need them both to be filled out...
Would the best way to do this to add a required to the end of both of the inputs when one is being filled out?
Keep in mind I'm already using JS to dynamically add more row's like that, with Item/Amount 2, 3, 4, etc...
I'm not sure how to go about this.
I would think the workflow would go like this:
1) upon being filled, find ID's of 'item' and 'amount' - eg... custom-item-1 and custom-amount-1
2) add 'required' to the inputs with the id's
Here's the code that I'm using to dynamically add row's incase it's useful:
// 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);
EDIT:
Final code:
// 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>