我正在尝试验证单选按钮组。如果不检查,则跨度将具有指示必须选择单选按钮的文本。问题是,。如果我将放射线按钮验证的代码置于顶部,它不起作用,但当它在下面时,。它的工作..有点奇怪,。这个的任何想法?感谢
$("#mchoice").submit(function () {
var direction = $('#direction').val();
var quiztxtBox = document.getElementsByName('quiztxtBox[]');
var isSubmit;
var names = [];
var err = document.getElementsByName('errMchoice[]');
// For radio button answers.
$('input[type="radio"]').each(function(){
names[$(this).attr('name')] = true;
});
if (!direction)
{
$('#direction').focus();
$('#direction').css({"background-color":"#f6d9d4"});
$('#direction').nextAll('span').html('Type in direction.');
event.preventDefault();
}
else
{
$('#direction').css({"background-color":"#fff"});
$('#direction').nextAll('span').html("");
}
for(correct_answer in names)
{
var radio_buttons = $("input[name='" + correct_answer + "']");
if( radio_buttons.filter(':checked').length == 0)
{
radio_buttons.nextAll('span').html('Select the answer.');
event.preventDefault();
}
else
{
radio_buttons.nextAll('span').html('');
}
}
// Choices fields
$("[name='quiztxtBox[]']").each(function(){
if (!this.value.length)
{
$(this).css({"background-color":"#f6d9d4"}).siblings('span.errorMsg').text('Please type in question/answer!');
event.preventDefault();
}
else
{
$(this).css({"background-color":"#fff"}).siblings('span.errorMsg').text("");
}
});
});
HTML here
<div id="QuestionTBDiv1" >
<label>Question</label><br/>
<input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
<label>Answer</label><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" class = "choiceA" name="correct_answer1" value="A">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B"> <input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer1" value="C">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D"> <input type="radio" class = "choiceD" name="correct_answer1" value="D"><br>
<span name="errMchoice" class="errorMsg"></span>
</div>
的jsfiddle: http://jsfiddle.net/Ej77L/2/
答案 0 :(得分:0)
您的javascript中存在一个小的逻辑错误。
设置带有“选择答案”错误消息的范围后,您正在检查问题是否已填写。如果已填充,则表示span text
为空。
因此,请保留一个标记,以查看是否选择了答案。如果未选中,则设置标志,并在代码的后续部分中,不要清空span text
这是一个有效的DEMO