Question

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>
Was it helpful?

Solution

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.

OTHER TIPS

@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.

  1. Put your JavaScript in script blocks, or better yet separate files, not inside HTML elements.
  2. Use jQuery to only deal with the one h2 at a time (as Barmar suggested).
  3. Do some reading how how jQuery selectors work. jquery.com documentation is very good, it will be time well spent.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top