New to jQuery, requesting assistance with something I’m having trouble figuring out.
A cloned table row contains an <input type="text" name="dt[]" id="dt1"> field. Below is the template row that gets cloned.
<table id="MyTable" name="MyTable">
<tr name="tr3" id="tr3">
<td>
<input type="text" name="dt[]" id="dt1">
</td>
<td>
<input type="file" name="fff[]" id="ff1">
</td>
</tr>
</table>
The user could potentially create several of these fields and I am trying to figure out how to loop through them all and verify there is text in them before submitting the form.
Note that I must use the jQuery .on() method to access the form elements. How would the loop need to be coded? Initially, I’ve been trying this (EDITED):
$(document).on('click','#sub1',function() {
var d1 = $("[name^=dt]").val();
alert(d1);
if (d1 !=""){
$("#TheForm").submit();
} else {
alert("Empty fields!");
}
});
And this:
var d1 = $("#dt1").val();
alert(d1);
And this:
var d1 = $("#^dt").val();
alert(d1);
but haven’t been able to get at the data.
EDIT: As requested, this code clones the row:
$(document).on('click', '#add_row', function() {
$("table#MyTable tr:nth-child(4)")
.clone()
.show()
.find("input, span").each(function() {
$(this)
.val('')
.attr('id', function(_, id) {
var newcnt = id + count;
return id + count;
});
})
.end()
.appendTo("table")
;
count++;
if (count == 2) {
$('#add_row').prop('disabled', 'disabled');
}
}); //end add_row Function
Your HTML is not in correct format. you should do:
and then loop over like:
What you’re trying to do can not be possible with
idattribute, but possible withnameattribute.idshould always be unique.Beside that
You can use a common
classname to allinputs and then loop over then like:Note
"#^dt"is not a valid selector at all. Correct syntax would be'input[name^=dt]'OR
input[id^=dt].You may implement the validation like below
Working sample
According to PROGRESS UPDATE
this.val()is wrong.Change this line to:
After a discussion in Chat and after solving the clone issue
Full code
Working sample