So i have 10 inputs dynamically created and i want do to a simple validation if they are not blank, the problem is that the code that i have does not work for these because they are not created at the page load.
how can i achieve this? Thx in advance
function submitForm() {
for(var i = 0; i < 10 ; i++){
if($("#input"+i).value == null){
alert("False!!");
}
}
}
You should use val() to check input value instead of value
(function() {
var i = 0;
$('button').click(function() {
$('body').append('<input type="text" id="input-' + i + '">');
i++;
});
$('input[type="submit"]').click( function() {
$('input[type="text"]').each(function() {
if ($(this).val() == '') {
alert($(this).attr('id') + ' is empty');
}
});
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="Submit">
<button>Create input</button>
You should use .val() instead of .value. I also suggest using .each(). Also when input is empty, its value is "" not null.
for(var i = 0; i < 10 ; i++) {
if($("#input"+i).val() == "") {
alert($("#input"+i).attr('id') + " is empty!")
}
}
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With