Question: jQuery Next Siblings Selector (“prev ~ siblings”)

Question

jQuery Next Siblings Selector (“prev ~ siblings”)

Answers 1
Added at 2016-12-28 17:12
Tags
Question

Html:

h4
  | Users
    button.btn.btn-primary.btn-xs.check_button aria-label=("Left Align") type="button"
     span.glyphicon.glyphicon-chevron-down aria-hidden="true"

.hsep

.form-group
  == collection_check_boxes :group, :user_ids, User.all, :id, :login do |b|
    == "<div class='checkbox'>#{b.label { b.check_box + b.text }}</div>"

h4
  | Domains
    button.btn.btn-primary.btn-xs.check_button aria-label=("Left Align") type="button"
     span.glyphicon.glyphicon-chevron-down aria-hidden="true"

.hsep

.form-group
  == collection_check_boxes :group, :domain_ids, Domain.all, :id, :domain_name do |b|
    == "<div class='checkbox'>#{b.label { b.check_box + b.text }}</div>"

Javascript:

$(".check_button").on("click", ->
 cbxs = $('h4 ~ .form-group').first().find('input[type="checkbox"]')
 cbxs.prop("checked", !cbxs.prop("checked"))
)

So it's a form where I got two checkbox list and I want a button for a each of them to check/uncheck all but I want this button to be generic as it's present in multiple views.

The javascript works fine but as you may have noticed, if the 2nd button is clicked, it checks/unchecks boxes from the first collection_check_boxes because of my $('h4 ~ .form-group') selector.

So what I want is not to use a raw h4 selector but use something like $(this).parent()first which will give me the right h4 element, my problem is how do I use $('h4 ~ .form-group') then? I can't make it work because I only know how to use it directly with h4 but I don't know how to actually change the h4.

It's a pretty simple problem I guess but I don't see how to use the jQuery( "prev ~ siblings" ) selector while changing my h4.

Answers to

jQuery Next Siblings Selector (“prev ~ siblings”)

nr: #1 dodano: 2016-12-28 17:12

You need to identify the h4 that is the parent of the clicked box.

One way to accomplish this is using closest combined with nextAll and first:

$(".check_button").on("click", ->
 cbxs = $(this).closest('h4').nextAll('.form-group').first().find('input[type="checkbox"]')
 cbxs.prop("checked", !cbxs.prop("checked"))
)
Source Show
◀ Wstecz