iamafish
iamafish

Reputation: 817

How to select other checkbox when the last value is checked

Here an example of my checkbox list http://jsfiddle.net/YnM2f/

Let's say I check on G then A,B,C,D,E,F also automatic checked. How can i achieve my goals with jQuery?

Upvotes: 1

Views: 661

Answers (5)

daveyfaherty
daveyfaherty

Reputation: 4613

Well it's already been done five times, but this is what I did: http://jsfiddle.net/YnM2f/27/

$('input').click(function(){
    if( $(this).is(':checked') ){
      $(this).parent('p').prevAll().children('input').attr('checked',true)

         }
})

Upvotes: 2

EvilAmarant7x
EvilAmarant7x

Reputation: 2069

This will check all checkboxes above a checkboxe that gets checked and uncheck all checkboxes above a checkbox that gets unchecked, given the checkbox layout that you've provided.

$('input:checkbox').click(function () {
    var state = $(this).prop('checked');
    var elements;
    if (state) {
        elements = $(this).parent().prevAll();
    } else {
        elements = $(this).parent().nextAll();
    }
    elements.each(function () {
        $('input:checkbox', this).prop('checked',state);
    });
});

Upvotes: 3

Ayman Safadi
Ayman Safadi

Reputation: 11552

Try something like this: http://jsfiddle.net/YnM2f/16/

It's a very specific solution (as in it will only work with "G"), but it should give you an idea for how to customize this code to meet your needs.

$('input:checkbox').filter(function(){
    return (/ G/).test($(this).parent().text())
}).on('change', function() {
    var gBox = $(this);
    $('input:checkbox').prop('checked', $(gBox).prop('checked'));
});

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78530

First you need to get all the checkboxes based on which one is clicked. for this you need to get the parent nodes, siblings that are before it. Here is some code that will help you get there, but you'll need to work on it to make it work for you.

http://jsfiddle.net/urau8/

$("input:checkbox").on("click",function(){
    if(this.checked)
    $(this).parent().prevAll().each(function(){
        $("input:checkbox",this).attr("checked",true);
    });
});

Upvotes: 4

Fernando Pereira
Fernando Pereira

Reputation: 31

$('input:checkbox').change(function(){
     var $allParents = $(this).parent();
     $allParents.prevAll().find('input').attr('checked', 'checked');
     $allParents.nextAll().find('input').removeAttr('checked');
});

Try this

Upvotes: 3

Related Questions