首页 > 解决方案 > 使用jquery选择复选框后表单按钮不起作用

问题描述

我添加了一个 jQuery 脚本来检查复选框是否被选中。如果检查做something和如果不做something else。这是我的 jQuery 代码:

jQuery('#mybtn').click(function (e) {
    e.preventDefault();                                         
    if (jQuery('#mytc').is(':checked')) {

        jQuery('#myfrm').attr('action', 'http://test.php');
                
        jQuery('#checkerror').html('');

    } else {
        jQuery('#checkerror').html('Please agree to the Terms and Conditions.');
    }

 });
<form id="myfrm">
  <p>Lorem ipsum dolor</p>
  <input type="checkbox" id="mytc" value=""/>
    <label class="yogatctxt">I agree to the <a href="#" target="_blank">Terms and Conditions</a>.</label><br>
  <span id="checkerror" style="color: red;font-size: 12px;"></span>
  <br>
   <br>
  <input type="submit" id="mybtn" value="Proceed to Checkout"/> 
</form>


<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

所以当我提交Process to Checkout button它仍然显示相同的页面。问题出在哪里?

标签: javascripthtmljquery

解决方案


在未选中复选框的情况下使用 prevent default 。

jQuery('#mybtn').click(function (e) {
                                            
    if (jQuery('#mytc').is(':checked')) {
        jQuery('#myfrm').attr('action', 'http://test.php');
            
        jQuery('#checkerror').html('');
        return true
    } else {
        e.preventDefault(); 
        jQuery('#checkerror').html('Please agree to the Terms and Conditions.');
        return false;
    }
});

推荐阅读