I have a list in HTML that holds the attributes data-answer and data-sum. The grid is populated with hidden answers. When a hidden answer is highlighted the user uses the sum to work out what the answer is. At the moment when an answer is highlighted the sum is not the correct one linked in the HTML, so the user cannot work it out.
What is wrong with my code, why won’t it pair these two attributes up. Is it because I haven’t set a variable for answers?
I have this list…
<ul style="display:none;" id="answerlist">
<li data-answer="1" data-sum="4 - 3 ="></li>
<li data-answer="2" data-sum="7 - 5 ="></li>
<li data-answer="3" data-sum="1 + 2 ="></li>
<li data-answer="4" data-sum="1 + 3 ="></li>
<li data-answer="5" data-sum="4 - 3 ="></li>
<li data-answer="6" data-sum="10 - 4 ="></li>
<li data-answer="7" data-sum="4 + 3 ="></li>
<li data-answer="8" data-sum="2 x 4 ="></li>
<li data-answer="9" data-sum="4 + 5 ="></li>
<li data-answer="10" data-sum="1 x 10 ="></li>
<li data-answer="11" data-sum="10 + 1 ="></li>
<li data-answer="12" data-sum="2 x 6 ="></li>
<li data-answer="13" data-sum="9 + 4 ="></li>
<li data-answer="14" data-sum="2 x 7 ="></li>
<li data-answer="15" data-sum="11 + 4 ="></li>
</ul>
The answer works fine, but when I go to pull the question into the div – “.sumstyle” it is always the wrong one to the question.
var sum = $('#answerlist li[data-answer=' + answer + ']').data('sum');
$('.sumstyle').text(sum);
Is there something wrong with the way I am setting the variable for sum?
Here’s a fiddle http://jsfiddle.net/ZAfVZ/21/
Ok, I’ve had a look at the Fiddle, and the reason this:
…on line 120 isn’t finding the li element you want is that the
answervariable being written into the JQuery selector has no value. This means you’re really doing this:…which is looking for the li element where the data-answer attribute has no value, which does not exist.
Where is the value of
answeron that line supposed to come from? There’s a localanswervariable used in the earlierfor / whileloop around line 100 – is that it?