Reputation:
I want to make it so that everytime you click on an 'h2' tag, the 'input' inside gets selected and the 'h2' tag changes background, but if another 'h2' tag is clicked, the current highlight and 'input' selection changes accordingly.
problem is that I have 3 different that do the same and with my code all the 3 forms are affected rather one. How do i limit my changes to only be contained to that form. Here is some code for clarification '
<form>
...
<h2 onclick="document.getElementById(1001).checked='True'
$('h2').removeClass('selected');
$(this).addClass('selected');
">
CONTENT
<input type="radio" name="radio" id="1001" value="1001" />
</h2>
...
</form>
Upvotes: 0
Views: 1174
Reputation: 781878
I think this is what you need:
$("form h2").click(function() {
var form = $(this).closest("form");
$("#"+$(this).text().trim()).prop('checked', true);
form.find('h2').removeClass('selected');
$(this).addClass('selected');
});
All the changes are confined to elements within this form.
Upvotes: 2
Reputation: 1619
@Barmar has answered this from a code perspective. Let's see about helping pass some knowledge on. There are some non-code concepts that will help you avoid this problem in the future.
This is a common, and very frustrating, mistake with understanding how JavaScript and HTML work together. The JavaScript doesn't full "belong" to the h2 element when you put it in the onclick attribute, it just runs when you click it. The JavaScript can touch anything in the rest of the page. That's why $('h2').removeClass()
is selecting every h2
element.
In general, you should do a few things to help your confusion.
h2
at a time (as Barmar suggested).Upvotes: 0