Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target content generated dynamically with jquery

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!!");
        }
    }
}
like image 831
Carolina Vicente Avatar asked Mar 15 '26 06:03

Carolina Vicente


2 Answers

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>
like image 150
Nenad Vracar Avatar answered Mar 17 '26 19:03

Nenad Vracar


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

like image 35
Somrlik Avatar answered Mar 17 '26 18:03

Somrlik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!