gpt4 book ai didi

javascript - 在用户提交表单之前,如何检查文本框和复选框是否已填写并选中?

转载 作者:行者123 更新时间:2023-11-28 17:56:55 24 4
gpt4 key购买 nike

下面显示了我的 JS 代码和我希望创建表单的部分 HTML。我找不到为什么当有未填写的字段时我仍然可以提交它的原因。它应该根据用户未填写的字段弹出一个对话框。

<script>
function validation() {
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
}
if( $('#agree').val() == null || $('#agree').val() == undefined || $('#agree').val() == ""){
alert( 'Please indicate that you have satisfied all the requirements');
}
}
</script>

<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>

<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" onclick="validation()" >
</div>
</div>
</div>

最佳答案

复选框验证错误。 IIS is(':checked')并应用简单的输入验证 !input value 其验证 null,empty,undefined .trim() 删除不需要的空白。

如果您有 from 标记,请尝试使用 onsubmit="returnvalidation()" 而不是 onclick="validation" 提交按钮。 return false 当输入失败时停止函数执行

function validation() {
if (!$('#sdate').val().trim()) {
alert('Please fill in start date field');
return false // if you have a form tag
}
if (!$('#edate').val().trim()) {
alert('Please fill in end date field');
return false // if you have a form tag
}
if (!$('#agree').is(':checked')) {
alert('Please indicate that you have satisfied all the requirements');
return false // if you have a form tag
}
else{
console.log('ok')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit="return validation()">
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>

<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" >
</div>
</div>
</div>
</from>

关于javascript - 在用户提交表单之前,如何检查文本框和复选框是否已填写并选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com