【问题标题】:how to tweak form validator.js to only send form if checkbox is checked如果选中复选框,如何调整表单 validator.js 以仅发送表单
【发布时间】:2019-09-25 05:49:11
【问题描述】:

我使用https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form 的示例制作了一个联系表格,效果很好。 现在我想添加一个复选框,如果用户希望能够提交表单,则必须检查该复选框(除了 google recaptcha 和必填表单字段)。

我想我必须调整 validator.js 文件,但由于我不懂 javascript,所以我不知道如何编辑现有的验证器文件。

附加复选框的 HTML:

<label>
<input type="chbox" name="chbox" id="chbox"><a href="terms.html">Terms and conditions</a>.
</label>

js:

function getValue($el) {
  return $el.is('[type="checkbox"]') ? $el.prop('checked')                                     :
         $el.is('[type="radio"]')    ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
                                       $el.val()
}

var Validator = function (element, options) {
  this.options    = options
  this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
  this.$element   = $(element)
  this.$btn       = $('button[type="submit"], input[type="submit"]')
                      .filter('[form="' + this.$element.attr('id') + '"]')
                      .add(this.$element.find('input[type="submit"], button[type="submit"]'))

  this.update()

  this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
  this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
  this.$element.on('reset.bs.validator', $.proxy(this.reset, this))

  this.$element.find('[data-match]').each(function () {
    var $this  = $(this)
    var target = $this.data('match')

    $(target).on('input.bs.validator', function (e) {
      getValue($this) && $this.trigger('input.bs.validator')
    })
  })

  this.$inputs.filter(function () { return getValue($(this)) }).trigger('focusout')

  this.$element.attr('novalidate', true) // disable automatic native validation
  this.toggleSubmit()
}

只有在填写了必填字段并进行了复选框和recaptcha检查时,提交按钮才应该可以点击并且可以提交表单。

【问题讨论】:

  • 您是否尝试过为表单字段提供必需的属性?或者在验证器中为该字段提供所需的规则?
  • 是的,表单的 ID 为 #contact-form。我在验证器中尝试了以下代码:this.$chbox = $("#contact-form").on('submit',function(){ if(document.getElementById("chbox").checked) { $("#contact-form").submit(); } else { e.preventDefault(); alert('please agree terms by checking the checkbox'); } }
  • @Taplar ...但是尽管未选中复选框,但仍会发送表单

标签: javascript jquery forms validation checkbox


【解决方案1】:

哦,我刚刚发现复选框的 html 不完整。我添加了required="required"。现在的完整行是 &lt;input type="checkbox" name="chbox" id="chbox" required="required"&gt; 现在终于按预期工作了。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2017-06-16
    • 1970-01-01
    • 2014-07-28
    • 2020-05-06
    相关资源
    最近更新 更多