Javascript 如何在引导程序中验证至少标记了一个复选框并将此信息传递给 php?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32681392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:04:31  来源:igfitidea点击:

How can I validate in bootstrap that at least one checkbox is marked and pass this information to php?

javascriptphpjquerytwitter-bootstrapvalidation

提问by randomuser1

I'm using bootstrap and I created a form with 8 checkboxes. When user clicks "Submit" I want to verify if at least one checkbox is marked and if not - let user know with an error message below the checkbox group. Also, I would like to verify if the date that he puts is correct with my default data-form: 23/09/2015 05:45 PM

我正在使用引导程序,并创建了一个带有 8 个复选框的表单。当用户单击“提交”时,我想验证是否至少标记了一个复选框,如果未标记 - 让用户知道复选框组下方的错误消息。另外,我想用我的默认数据表单验证他输入的日期是否正确:23/09/2015 05:45 PM

This is my java-script validation code:

这是我的java脚本验证代码:

$('#myform').validate({// initialize the plugin
    errorElement: 'div',
    rules: {
        datetimepicker: {
            required: true,
            date: true
        },
        commercialText: {
            required: true,
            minlength: 5
        },
        terms: {
            required: true,
            maxlength: 2
        }
    },
    submitHandler: function (form) { 
        var text = $("#customtext").val();
        var date = $("#datetimepicker").val();
        var stand = 2; 
        $.ajax({
            url: 'savedatanow.php',
            type: "POST",
            data: {
                text: text,
                date: date,
                stand: stand

            },
            dataType:'text',
            success: function(response)
            {

                alert(response);
            }
        });
        //alert('outside ajax');
    },
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('success').addClass('has-error');
    },
    success: function (element) {
        element.addClass('valid')
            .closest('.form-group').removeClass('error').addClass('has-success');
    }                   
});

I prepared the following fiddle: http://jsfiddle.net/5WMff/1316/but I have a problem with marking the correct error messages in red. When user doesn't check that he accepts the terms there's a weird situation happening too (the whole text is marked in red, not only the error)... Can you help me with that? Thanks!

我准备了以下小提琴:http: //jsfiddle.net/5WMff/1316/但我在将正确的错误消息标记为红色时遇到问题。当用户不检查他是否接受这些条款时,也会发生奇怪的情况(整个文本都标记为红色,而不仅仅是错误)......你能帮我解决这个问题吗?谢谢!

采纳答案by vanburen

You can name the checkbox array whatever makes sense (I used number[]as a generic example), then add your rules and/or messages as usual.

您可以为复选框数组命名任何有意义的名称(我用作number[]通用示例),然后像往常一样添加您的规则和/或消息。

You can use custom errorPlacement rules to add messages where appropriate. There's a target div for the checkbox array that's places in your HTML (<div id="checkboxGroup"></div>).

您可以使用自定义 errorPlacement 规则在适当的地方添加消息。复选框数组有一个目标 div,它位于 HTML ( <div id="checkboxGroup"></div>) 中。

See docs: jQuery Validate

请参阅文档:jQuery 验证

$('#myform').validate({
  rules: {
    datetimepicker: {
      required: true,
      date: true
    },
    commercialText: {
      required: true,
      minlength: 5
    },
    terms: {
      required: true,
      minlength: 1
    },
    'number[]': {
      required: true,
      minlength: 1,
      maxlength: 2
    }
  },

  messages: {
    datetimepicker: {
      required: "Please enter a date."
    },
    commercialText: {
      required: "Please enter your message."
    },
    terms: {
      required: "Please agree to terms."
    },
    'audit[]': {
      required: "Please check at least 1 option.",
      minlength: "Please check at least {0} option."
    }
  },

  submitHandler: function(form) {
    var text = $("#customtext").val();
    var date = $("#datetimepicker").val();
    var stand = 2;
    $.ajax({
      url: 'savedatanow.php',
      type: "POST",
      data: {
        text: text,
        date: date,
        stand: stand

      },
      dataType: 'text',
      success: function(response) {

        alert(response);
      }
    });
    //alert('outside ajax');
  },

  highlight: function(element) {
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
  },
  unhighlight: function(element) {
    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
  },

  errorClass: 'help-block',
  errorPlacement: function(error, element) {
    if (element.parent('.form-group').length) {
      error.insertAfter(element.parent());
    } else {
      error.insertAfter(element.parent());
    }
    if (element.attr('name') == 'number[]') {
      error.insertAfter('#checkboxGroup');
    } else {
      error.appendTo(element.parent().next());
    }
  }

});
#myform .has-error .help-block {
  display: block;
  border: none;
  color: #737373;
  padding-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/additional-methods.min.js"></script>
<div class="container">
  <form role="form" id="myform">
    <div class="form-group">
      <label>what is your number?</label>
      <div class="col-lg-12">
        <div class="col-lg-6">
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">one</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">two</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">three</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">four</label>
          </div>
        </div>
        <div class="col-lg-6">
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">five</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">six</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">seven</label>
          </div>
          <div class="checkbox">
            <label>
              <input name="number[]" type="checkbox" value="">eight</label>
          </div>
        </div>
      </div>
      <div id="checkboxGroup"></div>
    </div>
    <div class="form-group">
      <label for="datetimepicker">When do you want to go?</label>
      <input type="text" class="form-control" id="datetimepicker" name="datetimepicker" />
    </div>
    <div class="form-group">
      <label>How long will it last?</label>
      <select class="form-control">
        <option>5 seconds</option>
        <option>10 seconds</option>
        <option>15 seconds</option>
        <option>20 seconds</option>
        <option>30 seconds</option>
      </select>
    </div>
    <div class="form-group">
      <label for="commercialText">Write a text that:</label>
      <textarea class="form-control" rows="3" id="commercialText" name="commercialText" placeholder="hello"></textarea>
    </div>
    <div class="form-group">
      <label class="checkbox-inline">
        <input type="checkbox" id="terms" name="terms">I accept the terms</label>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

回答by Danijel

Create custom validator for group of elements.

为元素组创建自定义验证器。

$.validator.addMethod( "at_least_one", function() {
    return $( "input[name='number[]']:checked" ).length;
}, 'Select at least one number' );

Add rule.

添加规则。

rules: {
    "number[]": "at_least_one",
    .....

Add name and value attributes to checkboxes, here is an example of how to creates an array of the selected values with square braces to the checkbox names. That way $_POST['number']will be an array of checked values.

向复选框添加名称和值属性,这里是一个示例,说明如何使用方括号为复选框名称创建选定值的数组。这样$_POST['number']将是一组检查值。

<input type="checkbox" value="two" name="number[]">

UPDATED FIDDLE

更新的小提琴

For dates you can use jQuery Datepickeror THIS SOquestion, basically create another custom validation method.

对于日期,您可以使用jQuery DatepickerTHIS SOquestion,基本上创建另一个自定义验证方法。

Now, there is still some issues with error messages and bootstrap, I hope that someone else will help you with that.

现在,错误消息和引导程序仍然存在一些问题,我希望其他人能帮助您。