使用动态ID和名称验证动态生成的输入框

时间:2014-07-16 12:22:20

标签: javascript jquery validation dynamic-variables

我有一个按钮,可以添加两个输入字段onclick。以下是代码:

<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>

和JQuery是

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>");
})

如何在提交表单时验证这些动态添加的输入框是否为空值和正确值?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

$('.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
    }
  }
});