Finding the id of a parent div using Jquery
I have some html like this:
<div id="1">
<p>
Volume = <input type="text" />
<button rel="3.93e-6" class="1" type="button">Check answer</button>
</p>
<div></div>
</div>
and some JS like this:
$("button").click(function () {
var buttonNo = $(this).attr('class');
var correct = Number($(this).attr('rel'));
validate (Number($("#"+buttonNo+" input").val()),correct);
$("#"+buttonNo+" div").html(feedback);
});
What I'd really like is if I didn't have to have the class="1" on the button (I know numeric classes aren't valid, but this is a WIP!), so I could determine buttonNo based on the id of the parent div. In real life there are multiple sections looking like this.
How do I find the id of the div parenting the button.
What would be a more semantic way to store the answer in the button code. I want to make this as foolproof as possible for a non programmer to copy and paste without breaking things!
Solution 1:
You could use event delegation on the parent div. Or use the closest method to find the parent of the button.
The easiest of the two is probably the closest.
var id = $("button").closest("div").prop("id");
Solution 2:
1.
$(this).parent().attr("id");
2.
There must be a large number of ways! One could be to hide an element that contains the answer, e.g.
<div>
Volume = <input type="text" />
<button type="button">Check answer</button>
<span style="display: hidden">3.93e-6</span>
<div></div>
</div>
And then have similar jQuery code to the above to grab that:
$("button").click(function ()
{
var correct = Number($(this).parent().children("span").text());
validate ($(this).siblings("input").val(),correct);
$(this).siblings("div").html(feedback);
});
bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.
Solution 3:
Try this:
$("button").click(function () {
$(this).parents("div:first").html(...);
});