I'm creating a basic crossword using input fields within an HTML table and am looking to check whether the answer is correct using jQuery. If the answer is correct I also need to open dialog X and if the answer is incorrect I need to open dialog Y.
Taking the code snippet below as an example ...
<td><input name="r1c1" type="text" id="r1c1-input" maxlength="1"></td>
<td><input name="r1c2" type="text" id="r1c2-input" maxlength="1"></td>
<td><input name="r1c3" type="text" id="r1c3-input" maxlength="1"></td>
<td><input name="r1c4" type="text" id="r1c4-input" maxlength="1"></td>
<td><input name="r1c5" type="text" id="r1c5-input" maxlength="1"></td>
... how would I check that the following had been typed in to each field?
r1c1 = A
r1c2 = B
r1c3 = C
r1c4 = D
r1c5 = E
Many thanks.
The easiest way is to write a function that uses a basic loop and returns a Boolean value. Get the value of each input
field with $('#fieldId')
, compare it with your expected answers, and then base the next action on the value returned by the answer-checking function. Based on your example snippet, here's one way to do it:
var fields = ['r1c1', 'r1c2', 'r1c3', 'r1c4', 'r1c5'],
answers = ['A', 'B', 'C', 'D', 'E'];
var checkAnswers = function(fieldArray, answerArray) {
for (var i = 0; i < fieldArray.length; i += 1) {
if ($('#' + fieldArray[i] + '-input').val() !== answerArray[i]) {
// This field doesn't have the correct answer
return false;
}
}
// Made it all the way through the loop, so all answers match
return true;
}
if (checkAnswers(fields, answers)) {
// dialog X
} else {
// dialog Y
}