0

I have a button that adds two input field onclick. Below is the code:

<button type="button" class="btn btn-warning btn-xs" id="additem">
Click here to add Items</button>
<form>
<div id="inputboxes"></div>
<input type="submit">
</form>

and JQuery is

var i = 1,
    j = 1,
    k = 1,
    l = 1;
$("#additem").click(function () {
    $("#inputboxes").append("<div class='form-group'><input type='text' id='iname" +
        (j++) +
        "' name='iname" +
        (i++) +
        "' class='form-control'  placeholder='Enter Item Name' required='required'/></div> " +
        "<div class='form-group'><input type='text' id='iprice" +
        (k++) +
        "'   name='iprice" +
        (l++) +
        "' class='form-control'  placeholder='Enter Item Price' required='required'/></div>");
})

How can i validate these dynamically added input boxes for empty and correct values on submitting the form?

vol7ron
  • 40,809
  • 21
  • 119
  • 172
Gags
  • 3,759
  • 8
  • 49
  • 96
  • What did you try..? what do you mean by correct values..? what is the problem you're facing..? – T J Jul 16 '14 at 12:27
  • i tried validating by having 'iname' and 'iprice' but it didn't work. Correct values means in `Iteam Price` only digits are allowed. Problem is that fields are not getting validated – Gags Jul 16 '14 at 12:29
  • Try this answer for dynamic name fields and form validation http://stackoverflow.com/questions/27071413/dynamic-form-name-attribute-input-type-text-name-variable-name-in – SoEzPz Nov 21 '14 at 22:42

1 Answers1

0

You can do something like:

$('.form-group').each(function(){
  var input = $(this).children('input');
  if(input.val() == '' || input.val() == undefined){
    // the errors you will give
  }else{
    if(input.attr('id').substring(0, 5) == 'iname'){
      //function to validate your iname
    }else if(input.attr('id').substring(0, 6) == 'iprice'){
      //function to validate your iprice
    }
  }
});
Xlander
  • 1,331
  • 12
  • 24
  • Can u please add one function to add validate empty field – Gags Jul 17 '14 at 17:47
  • For checking empty input, it's in the `foreach` as follows: `if(input.val() == '' || input.val() == undefined){ // the errors you will give }` – Xlander Jul 17 '14 at 17:56
  • But it is not validating empty fields that are getting added by JQuery – Gags Jul 17 '14 at 18:37
  • When are you calling this function? – Xlander Jul 18 '14 at 05:30
  • i am calling this function click of submit button.. can u write a fiddle for better understanding – Gags Jul 18 '14 at 14:28
  • You have to put the function on the form submission. `$('#form').submit(function(){});` then if there is error you prevent the submission.. – Xlander Jul 19 '14 at 16:40
  • if we add `alert("Wrong");` after console.log in name not matching validation, then alert is not coming up. :( Please help – Gags Jul 25 '14 at 18:01