hasAttribute不动态更改

时间:2018-01-12 17:41:31

标签: javascript jquery jquery-validate

我目前在我的表单上使用jQuery Validator,在提交表单时,无论是选中还是未选中,checked属性都无法更改验证程序。

这是我的HTML:

<div class="col-sm-10 col-sm-offset-1">
    <div class="col-sm-6">
        <div class="choice" data-toggle="wizard-radio">
            <input type="radio" name="platform" value="P1">
            <div class="icon">
                <img src="{{ asset('images/platform1.png') }}" style="height: 100px;">
            </div>
            <h6>Platform 1</h6>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="choice" data-toggle="wizard-radio">
            <input type="radio" name="platform" value="P2">
            <div class="icon">
                <img src="{{ asset('images/platform2.png') }}" style="height: 100px;">
            </div>
            <h6>Platform2</h6>
        </div>
    </div>
    <label for="platform" class="error" style="display:none;">Please choose one.</label>
</div>

这是我的JS:

// Code for the Validator
var $validator = $('.wizard-card form').validate({
    rules: {
        platform: {
            required: function () {
                var checked = false;
                $('input[name="platform"]').each(function() {
                    if(jQuery(this)[0].hasAttribute('checked')) {
                        var checked = true;
                    }
                });
                console.log(checked);
                return checked;
            }
        }
    }
});

我甚至尝试使用return $('[name="platform"]:checked').length > 0;无效。

1 个答案:

答案 0 :(得分:2)

修改

也许你这里的任务过于复杂......

这个简单的规则应该有效:

$('.wizard-card form').validate({
  rules: {
    platform: "required"
  }
});
.error{
  outline:3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>

<div class="wizard-card">
  <form>
    <div class="col-sm-10 col-sm-offset-1">
      <div class="col-sm-6">
        <div class="choice" data-toggle="wizard-radio">
          <input type="radio" name="platform" value="P1">
          <div class="icon">
            <img src="https://via.placeholder.com/350x150" style="height: 100px;">
          </div>
          <h6>Platform 1</h6>
        </div>
      </div>
      <div class="col-sm-6">
        <div class="choice" data-toggle="wizard-radio">
          <input type="radio" name="platform" value="P2">
          <div class="icon">
            <img src="https://via.placeholder.com/350x150" style="height: 100px;">
          </div>
          <h6>Platform2</h6>
        </div>
      </div>
      <label for="platform" class="error" style="display:none;">Please choose one.</label>
    </div>
    <button id="done">Submit</button>
  </form>
</div>

我建议您更仔细地阅读the documentation