So, in a form I have multiple choice and therefore an array of answers that I need validate. My attempt at the code is this, but it just returns that ‘i’ (from the .each() line) is not defined:
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
}
I’ve played around with the code quite a bit just it’s just breaking jQuery when I do.
(Note: Assume $ for $j, it’s to avoid collisions with prototype on another section of the site.)
Solution:
// 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;
}
eachreturns a jQuery object which is always a “truethy” value.You can use
filter: