如果用户按下取消确认选择医生,我将如何阻止表单提交。
<form method="post" action="registration.php" autocomplete="off" onsubmit="return validateMyForm();">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="role" id="role">
<option value="Patient">Patient</option>
<option value="Doctor">Doctor</option>
<option value="Nurse" >Nurse</option>
</select>
<input type="submit">
</form>
<script>
$("#role").change(function(){
var val = $(this).val();
switch (val){
case "Doctor":
var d = confirm("Are you a doctor?");
}
});
</script>
答案 0 :(得分:1)
如果按下取消,您的d
变量将为false
,因此:
$("#role").change(function(){
let val = $(this).val();
let blockSubmit = false;
if (val == 'Doctor') {
let d = confirm("Are you a doctor?");
blockSubmit = !d;
}
else {
blockSubmit = false
}
$('input[type="submit"]').prop('disabled', blockSubmit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form method="post" action="registration.php" autocomplete="off" onsubmit="return validateMyForm();">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="role" id="role">
<option value="Patient">Patient</option>
<option value="Doctor">Doctor</option>
<option value="Nurse">Nurse</option>
</select>
<input type="submit">
</form>
答案 1 :(得分:1)
要停用表单提交,您可以在表单的return false
属性上使用onsubmit
。
由于您已经调用了validateMyForm()
函数,因此您只需要确保此函数返回false:
function validateMyForm() {
....
// do some checks...
return false;
}
如果您要根据confirm
的答案阻止提交表单,则应将答案保存在稍后可以使用的某个变量中:
<script>
var d;
$("#role").change(function(){
var val = $(this).val();
switch (val){
case "Doctor":
d = confirm("Are you a doctor?");
}
});
</script>
在函数内部:
function validateMyForm() {
if (!d) {
return false;
}
}