【发布时间】:2014-02-28 13:12:18
【问题描述】:
我有一个表单的 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");
}
});
});
});
【问题讨论】:
-
说真的,你每十分钟问一个完全不同的问题。告诉你的老板雇佣一些开发人员......
-
@A.Wolff:请不要误会我的意思,但我的最后期限很紧迫,没有人可以帮助我,所以我向一群专家寻求帮助。
-
"没有人来帮助我" 大多数时候你都有一些准确的答案。请不要误解我们,但我们不是来做你的工作的
标签: javascript jquery forms validation checkbox