Reputation: 1108
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/
Upvotes: 3
Views: 145
Reputation: 7135
Ok, I've had a look at the Fiddle, and the reason this:
var sum= $('#answerlist li[data-answer="'+answer+'"]').data('sum');
...on line 120 isn't finding the li element you want is that the answer
variable being written into the JQuery selector has no value. This means you're really doing this:
var sum= $('#answerlist li[data-answer=""]').data('sum');
...which is looking for the li element where the data-answer attribute has no value, which does not exist.
Where is the value of answer
on that line supposed to come from? There's a local answer
variable used in the earlier for / while
loop around line 100 - is that it?
Upvotes: 1
Reputation: 50832
Problem here is that the attribute data-sum
is a string and not an integer.
You will need to fetch the attribute and eval the variable in order to get the right sum.
Update: Once you get your attribute do
var attribute_value = "5 + 7 ="; // assumed attribute value
var solution = attribute_value.substring(0, attribute_value.length -2);
var sum = eval ( solution );
alert(sum);
Upvotes: 1