Reputation: 1039
These fields are created with JQuery.
How do I validate the array of "aname[]" fields (you have to fill them in before going to the next step)?
JQuery to HTML:
input ="<input name='aname[]' id='1' placeholder='yourname1' type='text' required />";
input +="<input name='aname[]' id='2' placeholder='yourname2' type='text' required />";
input +="<input name='aname[]' id='3' placeholder='yourname3' type='text' required />";
$(".placeholder").append(input);
JQuery command to try and get input
$(document).ready(function() {
var items = $('input[name="items[]"]').text();
if(items == ""){
alert("fill this field");
}
});
Upvotes: 1
Views: 73
Reputation: 1075755
Two issues:
text()
retrieves the text of an element (like a span
or div
), not the value of an input. To get the value of an input, use val
. (Or if just working with the DOM element, the value
property.)
You need to run the check in response to an event, not just on page load.
If you change text()
to val()
in that code, you'll only be checking the value of the first one (text()
is a bit odd and works differently to val()
and most other jQuery getters).
So if you want to check that all of them are filled in, you'll need an event handler and a loop of some kind:
$(document).ready(function() {
$("selector-for-the-form").on("submit", function(e) {
$(this).find('input[name="items[]"]').each(function() {
if (this.value == "") {
this.focus(); // So the user knows which field...
alert("fill this field"); // ...although this may mess that up
e.preventDefault(); // Prevent form submission
return false; // Stop looping
}
});
});
});
Of course, alert
isn't usually the greatest user experience for this sort of thing. It's usually more pleasant if you do proactive validation and a notification that doesn't jar the user and interrupt what they're doing until you have to (like changing the color of the border of the input and/or showing an inline message). (There are also lots of plugins available to help you with doing that.)
Upvotes: 2