Reputation: 237
I have a form on asp.net with dynamically created table rows on button click with javascript. The problem I'm having is that those dynamic table rows are optional to fill in by users so it can either be filled or left blank when the form is submitted.
What is a good way to check for validation based on the user's input so if a user enters something in one textbox of the dynamically added table row then that means the other textbox needs to be validated and therefore should not allow the user to submit the form.
Javascript:
$btnAddTableRow.click(function() {
var html = '<tr>' +
'<td><input type="text" class="dynamicText" id="txtName' +
idCounter +
'"/></td>' +
'<td><input type="text" class="dynamicText" id="txtEmail' +
idCounter +
'"/></td>' +
'</tr>';
$($tblMembers).append(html);
idCounter++;
});
So as you can see on the code, each button click will add a new table row with 2 textboxes for name and email which are optional for users to fill in. The only way I can think of right now is to do an if else statement to check for each box but that seems very inefficient. My validation would be something like put a red border around the textbox that needs to be filled in if a user do submit the form without filling in one of the textboxes if another one is already filled in.
Thanks!
EDIT:
$('#showCounter').click(function () {
for (var i = 1; i < idCounter; i++) {
if ($('[id$="txtName' + i + '"]').val() !== "" || $('[id$="txtName' + i + '"]').val() !== null) {
console.log($('[id$="txtName' + i + '"]').val());
}
}
});
Upvotes: 0
Views: 249
Reputation: 306
While creating element concate row number to class="dynamicText".(dynamicText + rownumber). do not forget to increase variable.
On validation(or submit) check the rownumber and iterate it rownumber times. While it iterates in the loop fetch all elements with class "dynamicText" and rownumber in the loop, so you will get elements with class dynamicText1 or dynamicText2 etc... it will be array of elements.
Then within loop check if any of textbox has value then other textbox must be filled.
Upvotes: 1