gpt4 book ai didi

javascript - 为什么满足if条件后还要进入else部分?

转载 作者:行者123 更新时间:2023-11-28 19:58:26 27 4
gpt4 key购买 nike

我已经跟踪了表单的 HTML 代码:

<form name="question_issue_form" id="question_issue_form" action="question_issue.php">
<table class="trnsction_details" width="100%" cellpadding="5">
<tbody>
<tr>
<td></td>
<td>
<input type="checkbox" name = "que_issue[]" value = "Question is wrong" id ="chkQueWrong">Question is wrong</input>
</td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Answers are wrong" id ="chkAnsWrong">Answers are wrong</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Question direction is incorrect" id ="chkDirIncorrect">Question direction is incorrecct</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Other" id ="chkOther">Other</input></td>
</tr>
<tr>
<td></td>
<td class="set_message" style="display:none;"><textarea name="que_issue_comment" rows="4" cols="25" maxlength="100"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" id="report_question_issue"/></td>
</tr>
</tbody>
</table>
</form>

我想在提交表单之前验证表单,以便从上述所有复选框中至少选中一个复选框,并且当选中值为“其他”的复选框时,文本区域不应为空。为此,我尝试了以下代码,但即使在选择一个或多个复选框后它也会显示警报。此外,文本区域验证也无法正常工作。有人可以帮我在提交表单之前更正此验证码吗?如果抛出一个错误,则不应提交表单。以下是我尝试过的 jQUery 代码。

$(document).ready(function () {
$('#chkOther').click(function () {
$('.set_message').toggle(this.checked);
});

//This function is use for edit transaction status
$(document).on('click', '#report_question_issue', function (e) {

e.preventDefault();

//$.colorbox.close();

//for confirmation that status change
var ans = confirm("Are you sure to report the question issue over?");
if (!ans) { //alert("Yes its false");
return false;
}

var post_url = $('#post_url').val();

var checkbox = document.getElementsByName("que_issue[]");

var checkedAtLeastOne = false;

$('input[type="checkbox"]').each(function () {
if ($(this).is(":checked")) { alert("In If");
//atleast one is checked
checkedAtLeastOne = true;
} else { alert("In Else");
//error
alert("Check at least one checkbox");
}

var other = document.getElementById("chkOther");
var textfield = document.getElementByName("que_issue_comment");
if ($(other).is(":checked")) {
if ($(textfield).val().length == 0) {
//error
alert("Fill in the textarea");
}
}
});

$.ajax({
type: "POST",
url: post_url,
data: $('#question_issue_form').serialize(),
dataType: 'json',
success: function (data) {
alert("The values have been inserted");
}
});
});
});

最佳答案

if 语句执行多次,每个复选框执行一次。即使已选中另一个复选框,您也会看到每个未选中的复选框的警报。你需要彻底改变逻辑;迭代所有这些以查找选中的复选框,并在找到一个后立即停止迭代。

然后,在检查完所有这些之后,确定是否需要显示警报。

关于javascript - 为什么满足if条件后还要进入else部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096156/

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