JQuery get class name by private name

Hello I am creating a script to check the checkboxes of all subordinate checkboxes associated with the main one. This will be done using classes. So the master flags will have classes like "master1", "master2", etc. The associated slave flags will be class "slave1" (associated with master1), "slave2" (associated with master2), and so on.

so I'll start with:

jQuery('.checks_div input[type="checkbox"].^="master"').click(function(){

      

So, when the master has been clicked, I want to select all of the slaves associated with it and check them. But how?

thank

+3


source to share


2 answers


$('input[type="checkbox"][class^="master"]').on("click",function(){})

      

but delegation is better

$(document.body).on('click','input[type="checkbox"][class^="master"]',function(){})

      

then inside the click function, and if you have slaves in the adjacent div for master, check the box

var $slaves=$(this).next().find('input[type="checkbox"][class*="slave"]')

      

if the html differs well, you can select those subordinates from that $ (this) that was just marked.



once your subordinates are in a jquery object to check them:

$slaves.prop('checked', true);

      

see Setting "checked" for a checkbox with jQuery?

if you're not doing anything other than validation, you don't even need to cache your subordinates in the jquery object

 $(this).//chain to select slaves
        .prop('checked', true)

      

+3


source


Well here is the code I came up with:

$(document.body).on('click','input[type="checkbox"][class^="master"]',function(){
  var slaves = $(this).next('label').next('div.slaves').find('input[type="checkbox"][class*="slave"]');
  var master = $(this);
  $(slaves).attr('checked', $(this).is(':checked'));
});

      

This works great. Although I found there might be a bug in jQuery version 1.9.0 and up. Here is: http://jsfiddle.net/x3NpL/



1.8.3 works great, if u go above it will work twice and stop working. Very strange. Btw this doesn't happen if $ (slaves) .click () is used but click () doesn't have the desired result.

Anyway, the solution I used was to add a div to include the corresponding subordinates, but I would still like to know how to do this without the div. The idea is simple: catch the click on the master, get its class number (master14 - number 14, etc.), Check all slaves with this number (slave14). I just don't understand how to get the number from it, given the fact that a class can contain more than one class, like class = "class1 class2 master14" ..

thank

0


source







All Articles