在一行表中验证动态添加的输入类型

时间:2016-05-26 06:29:20

标签: javascript jquery

我正在尝试验证动态添加的输入类型字段,这些字段位于按钮单击事件的表格行中。第一个输入类型字段有一个ID,所以我可以对它进行验证。但是当我动态地在表中添加更多行时,我不知道如何验证那些输入类型的行。

HTML:

<table class="table table-bordered table-hover" id="tab_logic">
                <thead>
                    <tr>

                        <th class="text-center">Channel Group Name
                        </th>
                        <th class="text-center">Description
                        </th>

                    </tr>
                </thead>
                <tbody>
                    <tr id='addr0'>

                        <td id="CGN">
                            <input type="text" id="channelgrpName" name='channelgrpName' placeholder='Channel Group Name' class="form-control" />
                        </td>
                        <td id="DES">
                            <input type="text" id="description" name='description' placeholder='Description' class="form-control" />
                        </td>

                    </tr>
                    <tr id='addr1'></tr>
                </tbody>
            </table>

Jquery:

$(document).ready(function () {

    var i = 1;
    $("#add_row").click(function () {

        $('#addr' + i).html("<td><input name='name" + i + "' type='text' placeholder='Channel Group Name' class='form-control' style='width:50%'  /> </td><td><input  name='mail" + i + "' type='text' placeholder='Description'  class='form-control' style='width:50%'></td>");

        $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
        i++;
    });
    $("#delete_row").click(function () {
        if (i > 1) {
            $("#addr" + (i - 1)).html('');
            i--;
        }
    });
});

$('#btnSave').click(function () {

 // what should i to do here to validate dynamically added input types in row

});

提前致谢。

3 个答案:

答案 0 :(得分:1)

试试这个,如果你只需要检查空白

像这样:

$('#btnSave').click(function () {
  var validate = true;
    $('#tab_logic').find('tr input[type=text]').each(function(){
    if($(this).val() == ""){
        validate = false;
    }
  });
  if(validate){
    alert("Form is validate")
    return true;// you can submit form or send ajax or whatever you want here
  } else {
    alert("please fill all the details")
    return false;

  }
});

Js Fiddle for check blank fileds

如果您需要更多验证,只需使用一些js插件进行验证,如

jQuery-Validation-Engine

答案 1 :(得分:1)

please check this link i hope this will helpful for you. 

https://jsfiddle.net/ffgbvsg0/

答案 2 :(得分:0)

您根本不需要ID。

在第一行中,当您追加新行时,请为其指定一个类,例如:added-row

并绑定#tab_logic tbody tr.added-row上的点击监听器