I have this Javascript code where I want the users submission to only be pushed to the database, when all of the values are filled. The only problem is, a user can input a new row of data and that needs to be checked with a loop. Every time I go to click submit, the data is pushed regardless if the fields are filled or not. And it loops each time. I've tried moving data.push(assetInfo);
outside the brackets and it still prints submission accepted how ever many times the user clicks submit. Any help would be appreciated!
$('#submit').click(() =>{
$('form').on('submit', function(e){
e.preventDefault();
//Format all Data into JSON for Submission
let data = [];
// Iterate over all rows and store data
for (let i = 1; i <= count; i ){
// Skip Row if it was Removed
if (!$(`tr[index=${i}]`).length) continue;
// Store all Info from this row
let assetInfo = {
asset_tag_no: $(`#asset_tag_no${i}`).val(),
manufacturer: $(`#manufacturer_serial_no${i}`).val(),
descriptions: $(`#description${i}`).val(),
costs: $(`#cost${i}`).val(),
po_no: $(`#po_no${i}`).val(),
remarks: $(`#remarks${i}`).val(),
}
if (assetInfo.asset_tag_no && assetInfo.manufacturer && assetInfo.descriptions && assetInfo.costs && assetInfo.po_no && assetInfo.remarks != ''){
alert('Submission Accepted');
}
// Add Info to array
data.push(assetInfo);
}
// Upload JSON to Database
console.log(data);
});
});
})
CodePudding user response:
You don't need to move the push
outside the brackets. You need to move it inside the brackets:
if (assetInfo.asset_tag_no && assetInfo.manufacturer && assetInfo.descriptions && assetInfo.costs && assetInfo.po_no && assetInfo.remarks != ''){
alert('Submission Accepted');
// Add Info to array
data.push(assetInfo);
}
EDIT
If you want to push a row exactly once, then you can replace
if (!$(`tr[index=${i}]`).length) continue;
with
let currentRow = $(`tr[index=${i}]`);
if ((!currentRow.length) || (currentRow.hasClass("submitted"))) continue;
currentRow.addClass("submitted");