javascript - 使用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
它仍然显示相同的页面。问题出在哪里?
解决方案
在未选中复选框的情况下使用 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;
}
});
推荐阅读
- animation - 当 PIXI.Sprite 到达某个位置时如何动态更改 PIXI.Sprite 的纹理 - Pixi.js?
- python - PyQt5 项目结构和 PyInstaller ModuleNotFoundError
- https - MINIFI CPP 无法调用 HTTPS
- ios - Objective-c App 在 iOS 13 中崩溃(搜索栏问题)
- python-3.x - 调用帮助函数有什么问题?
- angular - @ngrx/entity `Cannot read property 'ids' of undefined` 与 @ngrx/store 一起使用时?在定义适配器时已经考虑了自定义 ID
- reactjs - 如何将多个复选框添加到一个状态
- c# - 如何在 Linq 语句中获取多个链接子项的父/源项?
- java - Android无法在内部存储上创建目录
- scala - Array((1L, 2L)) 是做什么的?