0
0
0348raven2015-10-08 13:55:44
JavaScript
0348raven, 2015-10-08 13:55:44

How to execute JS in a single block without involving other similar ones?

I have some filter with checkboxes. In each separate block of this filter, there is an element that, when becoming active, must remove activity from others, but only strictly in this block without affecting the elements of other similar blocks.
I have an understanding that you need to choose the parent closest element. But it doesn't work for me, I'm looking for help.

$("input[type=checkbox]").change(function () {

    var parent = $(this).closest('label');
    var parentBlock = parent.closest($('.search-form__checkbox'));

    parent.toggleClass('checked', $(this).is(':checked'));

    if (parent.hasClass("any") && parent.hasClass("checked")) {
      parentBlock.find($(".js-checkbox").not(parent).removeClass('checked'));
      parentBlock.find($(".js-checkbox").not(parent).find("input[type=checkbox]").attr("checked", false));
    } else if (!parent.hasClass("any") && parent.hasClass("checked")) {
      parentBlock.find($(".js-checkbox.any").removeClass('checked'));
      parentBlock.find($(".js-checkbox.any").find("input[type=checkbox]").attr("checked", false));
    }

  });

If you need any more information, I will provide it below in the comments.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2015-10-08
@0348raven

Something strange is happening in your code. It should be like this - https://jsfiddle.net/koceg/rt190edj/1/
I've simplified your code a bit to make it clearer.
Here is a very strange piece. You seem to be confused with brackets here. Notice what is being passed to parentBlock.find() .

E
Evgeny Petrov, 2015-10-08
@EvgenZZ

add the active class to the block before the change event, then $("input[type=checkbox]"), so Jquery will process the current block + add the selector that the InputBox is in the block with active

A
Andrey, 2015-10-08
@f-end

I would create an object with methods that define the behavior of all the elements in each individual block.
Then each block would have attached its own instance of this object.
And thus all blocks will be isolated from others - they each have their own object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question