javascript - 使用 jquery 选择复选框后表单按钮不起作用

标签 javascript html jquery

我添加了一个 jQuery 脚本来检查复选框是否被选中。 如果选中做某事,如果不做做其他事情。 这是我的 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>

因此,当我提交处理结账按钮时,它仍然显示相同的页面。问题出在哪里?

最佳答案

在未选中该复选框的情况下使用阻止默认值。

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;
    }
});

关于javascript - 使用 jquery 选择复选框后表单按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64423427/

相关文章:

javascript - 用js改变每个按钮的背景颜色

javascript - 如何在 ENTER/RETURN keydown 上提交文本区域

Javascript 将类添加到元素内的 <i>

javascript - 通过类名获取某个 div 内的元素

jquery - 需要一些帮助 - Drupal 6 网站上的某些东西破坏了 IE

javascript - 将数据插入 Flot

javascript - 如何自动关闭 Bootstrap 4 下拉菜单中的子菜单

javascript - 3 列布局自动中列宽度

php - 使用 php 更新 json

javascript - 如何将 html 转换为 javascript 字符串标记