因此,在一个表格中,我有多项选择,因此我需要验证一系列答案。我对代码的尝试是这样的,但它只是返回未定义“i”(来自 .each() 行):
function validTextAnswers(i, answer){
var answer = $j(this)
// ^ may not be needed, but I was using it
// when I was not passing arguements
if( (answer.val()=="") || (textAnswers.val()==null )){
alert('Note: Please fill in all answers.'),
answer.focus()
return false;
}
return true;
}
function validQuizCreate(){
var course = $j('#course-selection .selected')
var question = $j('textarea[name="question"]')
var textAnswers = $j('div.answer:visible').children('input[type="text"]');
if( (question.val()=="") || (question.val()==null) ){
alert('You have to supply a question.'),
question.focus()
return false;
}
if( !textAnswers.each(validTextAnswers(i, answer)) ){
console.log('all seems good!')
return false
}
我已经玩了很多代码,只是当我这样做时它只是破坏了 jQuery。(注:假设 $j 为 $,这是为了避免与网站另一部分的原型发生冲突。)
解决方案:
// jQuery filter() can be used for this:
var validTextAnswers = textAnswers.filter(function(){
return this.value != '';
}).length == '4'; // four because the test is A though D.
// If all 4 multiple choice answers are not empty, it returns true.
// so to use it I can say:
if(!validTextAnswers){
alert('Please fill in all multiple choice options.')
return false;
}