使用jquery验证克隆的复选框和单选按钮

时间:2016-12-15 06:37:29

标签: javascript jquery html validation checkbox

我正在尝试使用JQuery验证克隆的表单元素。以下是我的代码:

HTML:

<form class="form-inline">

        <div class="panel panel-default">

            <div class="panel panel-heading">
                Yii2 Form Clone Html                
                <a href="#" class="add btn btn-sm btn-success pull-right">Add</a>                
            </div>

            <div class="panel panel-body">

                <div class="form-section">

                    <div class="row" style="margin-top: 20px;">
                        <div class="col-md-3">
                            <div class="form-group">                
                                <input type="text" class="name form-control" placeholder="Username" id="name" name="username[]">                                
                                <span class="error"></span>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">                
                                <select name="city[]" class="form-control" class="city" id="city">
                                    <option value="">Select City</option>
                                    <option value="Pune">Pune</option>
                                    <option value="Mumbai">Mumbai</option>                        
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="checkbox-inline">
                                    <input type="checkbox" class="edu" value="MBA" name="edu[0]" id="edu"> MA
                                </label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" class="edu" value="MA" name="edu[0]" id="edu"> MA
                                </label>
                                <span class="error"></span>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label class="radio-inline">
                                    <input type="radio" name="gender[0]" id="gender" value="Male" class="gender"> Male
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender[0]" id="gender" value="Female" class="gender"> Female
                                </label>                    
                                <span class="error"></span>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">                
                                <input type="file" placeholder="Name" name="photo[]" id="photo" class="photo">
                                <span class="error"></span>
                            </div>
                        </div>


                    </div>
                </div>

            </div>
        </div>

        <input type="submit" name="submit" value="Submit" class="submit btn btn-primary">

    </form>

JQuery代码:

$(document).ready(function () {
        //Create a variable "clonedTemplate" 
        var clonedTemplate = $(".form-section .row:first").clone();
        var removeLink = "<div class='col-md-1'><div class='form-group pull-right'><a href='#' class='btn btn-sm btn-danger delete'>x</a></div></div>";
        var index = 0;


        $("body").on('click', '.add', function () {

            index++;
            var formSection = clonedTemplate.clone().find(':input').each(function () {
                var oldId = $(this).attr('id'); // getting "id" attribute
                var newId = oldId + "_" + index;  // generating new id
                $(this).attr('id', newId); // updating "id" field

                if ($(this).attr('type') === "radio") {
                    var prefix = "gender[" + index + "]";
                    $(this).attr('name', prefix); // updating "name" field
                }

                if ($(this).attr('type') === "checkbox") {
                    var prefix = "edu[" + index + "]";
                    $(this).attr('name', prefix); // updating "name" field
                }

            });

            formSection.end().appendTo('.form-section');
            $(".form-section .row:last").append(removeLink);

        });

        $("body").on("click", ".delete", function () {
            $(this).closest(".row").remove();
        });



        $("body").on("click", ".submit", function () {
            $(".form-section").find(":input").each(function (i) {
                var type = $(this).attr('type');
                //console.log(type);
                var errorTag = $(this).closest('.form-group').find('.error');
                var val = $(this).val();
                switch (type)
                {
                    case "text":
                        if (val === "")
                            errorTag.html("Username cannot be blank.");
                        else
                            errorTag.html("");
                        break;
                    case "file":
                        if (val === "")
                            errorTag.html("Photo cannot be blank.");
                        else
                            errorTag.html("");
                        break;
                    case "radio":
                        if ($(this).closest(".gender").prop('checked') !== true)
                            errorTag.html("Gender cannot be blank.");
                        else
                            errorTag.html("");
                        break;
                    case "checkbox":
                        if ($(this).closest(".edu").prop('checked') !== true)
                            errorTag.html("Education cannot be blank.");
                        else
                            errorTag.html("");
                        break;
                    default:
                        $(this).val("");
                }

            });
            return false;
        });

    });

我在验证克隆的radiobuttons和复选框时遇到问题。它只在我选择所有单选按钮/复选框或最后一个时才有效。如果我选择第一个radiobutton /复选框,则显示验证错误。

我在这里使用jquery closest()来逐行验证,因为在点击“添加”按钮后表格被克隆(添加行)。

检查以下小提琴:

https://jsfiddle.net/KJO/6vLdzzq4/2/

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

我稍微修改了你的代码,

修改了switch语句中的复选框和单选按钮,

(我认为您验证表单的方法不是最佳解决方案)

$(document).ready(function() {
  //Create a variable "clonedTemplate" 
  var clonedTemplate = $(".form-section .row:first").clone();
  var removeLink = "<div class='col-md-1'><div class='form-group pull-right'><a href='#' class='btn btn-sm btn-danger delete'>x</a></div></div>";
  var index = 0;


  $("body").on('click', '.add', function() {

    index++;
    var formSection = clonedTemplate.clone().find(':input').each(function() {
      var oldId = $(this).attr('id'); // getting "id" attribute
      var newId = oldId + "_" + index; // generating new id
      $(this).attr('id', newId); // updating "id" field

      if ($(this).attr('type') === "radio") {
        var prefix = "gender[" + index + "]";
        $(this).attr('name', prefix); // updating "name" field
      }

      if ($(this).attr('type') === "checkbox") {
        var prefix = "edu[" + index + "]";
        $(this).attr('name', prefix); // updating "name" field
      }

    });

    formSection.end().appendTo('.form-section');
    $(".form-section .row:last").append(removeLink);

  });

  $("body").on("click", ".delete", function() {
    $(this).closest(".row").remove();
  });



  $("body").on("click", ".submit", function() {

    var radioChecked = false;

    $(".form-section").find(":input").each(function(i) {
      var type = $(this).attr('type');
      //console.log(type);

      var errorTag = $(this).closest('.form-group').find('.error');
      var val = $(this).val();
      switch (type) {
        case "text":
          if (val === "")
            errorTag.html("Username cannot be blank.");
          else
            errorTag.html("");
          break;
        case "file":
          if (val === "")
            errorTag.html("Photo cannot be blank.");
          else
            errorTag.html("");
          break;
        case "radio":

          if (!$("input[name='" + $(this).attr('name') + "']:checked").val())

            errorTag.html("Gender cannot be blank.");
          else
            errorTag.html("");
          break;
        case "checkbox":
          if (!$("input[name='" + $(this).attr('name') + "']:checked").val())
            errorTag.html("Education cannot be blank.");
          else
            errorTag.html("");
          break;
        default:
          $(this).val("");
      }

    });
    return false;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body-content">
  <form class="form-inline">

    <div class="panel panel-default">

      <div class="panel panel-heading">
        Yii2 Form Clone Html
        <a href="#" class="add btn btn-sm btn-success pull-right">Add</a>
      </div>

      <div class="panel panel-body">

        <div class="form-section">

          <div class="row" style="margin-top: 20px;">
            <div class="col-md-3">
              <div class="form-group">
                <input type="text" class="name form-control" placeholder="Username" id="name" name="username[]">
                <span class="error"></span>
              </div>
            </div>

            <div class="col-md-2">
              <div class="form-group">
                <select name="city[]" class="form-control" class="city" id="city">
                  <option value="">Select City</option>
                  <option value="Pune">Pune</option>
                  <option value="Mumbai">Mumbai</option>
                </select>
              </div>
            </div>

            <div class="col-md-2">
              <div class="form-group">
                <label class="checkbox-inline">
                  <input type="checkbox" class="edu" value="MBA" name="edu[0]" id="edu">MA
                </label>
                <label class="checkbox-inline">
                  <input type="checkbox" class="edu" value="MA" name="edu[0]" id="edu">MA
                </label>
                <span class="error"></span>
              </div>
            </div>

            <div class="col-md-2">
              <div class="form-group">
                <label class="radio-inline">
                  <input type="radio" name="gender[0]" id="gender" value="Male" class="gender">Male
                </label>
                <label class="radio-inline">
                  <input type="radio" name="gender[0]" id="gender" value="Female" class="gender">Female
                </label>
                <span class="error"></span>
              </div>
            </div>

            <div class="col-md-2">
              <div class="form-group">
                <input type="file" placeholder="Name" name="photo[]" id="photo" class="photo">
                <span class="error"></span>
              </div>
            </div>


          </div>
        </div>

      </div>
    </div>

    <input type="submit" name="submit" value="Submit" class="submit btn btn-primary">

  </form>



</div>

答案 1 :(得分:1)

1,使用tableView查询

虽然这种方式表现不佳。 $(“。gender:checked”)将返回已检查的所有.gender无线电。

ViewDidLoad

https://jsfiddle.net/6vLdzzq4/3/

2,序列化

如果您想重写代码,可以尝试使用Jquery序列化表单数据,然后根据结果进行验证

issuesTableView.dataSource = self
issuesTableView.delegate = self

如果选中了任何复选框或单选框,则:check中将显示具有给定名称的对象。