提交表单检查复选框是否已选中

时间:2014-01-31 21:49:16

标签: javascript jquery html

我使用表单进行注册,并使用带有“使用条款”的复选框

 <form action="/signup/signup_success.html" id="regform" class="form-horizontal" novalidate="novalidate" autocomplete="off">
  <fieldset>
  <div class="checkbox">
                        <label for="agb" id="checkbox_validate" class="hide success">Please accept Terms of Use</label>
                        <label>
                            <input type="checkbox" name="agbcheckbox" id="agbcheckbox">
                            Yes <a target="_blank" href="http://example.de">Datenschutzbestimmungen</a>. </label>
                    </div>
                    <div class="buttonWrapper">
                        <button type="submit" class="try-button" >
                            Register
                        </button>
                    </div>
    </fieldset>
</form>

<script>
 //check if checkbox for terms of use is checked or not
 $("#regform").submit(function(event) {
if ($('#agbcheckbox').prop('checked')) {
    $('#checkbox_validate').removeClass('show').addClass('hide');
    //checkbox for terms of use is checked
} else {
    //checkbox for terms of use is NOT checked
    $('#checkbox_validate').removeClass('hide').addClass('show');
}
  });
</script>

如果我将“action =”/ signup / signup_success.html“添加到我的表单中,则复选框验证将不再有效。如果我将操作设置为action =”“验证工作正常。我找不到问题。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

这就是你需要的

event.preventDefault();

http://jsfiddle.net/ergec/L8Y8s/

同时建议您阅读此内容,以便更好地了解event.preventDefaultreturn false

之间的区别

event.preventDefault() vs. return false

答案 1 :(得分:0)

发现问题 - 我的功能错过了返回false;

答案 2 :(得分:0)

无论action ='...'存在与否,您的验证仍然有效。不同之处在于,当您定义了action ='...'时,浏览器将按指示发布您的表单。为了防止在验证失败时发生这种情况,请调用e.preventDefault()

eg) $("#regform").submit(function(e){ if (.. validation failes ...) { .. do your error msg here e.preventDefault() // prevent browser to perform default action (in this case submit the form) } });

相关问题