Welcome Guest, Not a member yet? Register   Sign In
[solved] How to handle an 'any' checkbox with Javascript?? [inc example]
#1

[eluser]umbongo[/eluser]
How can i make my 'any' checkbox deselect when any other checkbox (from the same group) is selected, and reselect when all others are deselected?? (initially selected as default)

The behavoir I want can be found at newegg's powersearch (eg http://www.newegg.com/Product/PowerSearc...GASearch=3 )
#2

[eluser]umbongo[/eluser]
anyone??
#3

[eluser]Twisted1919[/eluser]
you can use jquery on this , let's say you have something like :
Code:
Any : <input type="checkbox" name="product_type" value="any" class="group1" />
Retail : <input type="checkbox" name="product_type" value="retail" class="group1" />
Oem : <input type="checkbox" name="product_type" class="group1" value="oem" />
Open Box : <input type="checkbox" name="product_type" class="group1" value="open box" />
Recertified: <input type="checkbox" name="product_type" class="group1" value="recertified"/>

//[removed]
$('.group1').click(function(){
  
  if($(this).is('checked') == false){
      if($(this).val() == 'any'){
         $('.group1').removeAttr('checked');
         $(this).attr('checked',true);
      }
  }else{
      $('.group1').removeAttr('checked');
      $('.group1:first').attr('checked',true);
  }

});
It is not tested, it's from the top of my head, but you should get the idea and make your own solution .
#4

[eluser]umbongo[/eluser]
[edit:] code fixed, see below..
#5

[eluser]umbongo[/eluser]
OK i fixed the code so here it is for anyone who might arrive here through google or similar;
Code:
<skript type="text/javascript">
$('.group1').click(function(){

    if($(this).is(':checked')){                //if a checkbox is checked..
        if($(this).val() == 'any'){                //if it has the value 'any'
            $('.group1').removeAttr('checked');     //uncheck all this group
            $(this).attr('checked', true);            //then check 'any' box
        }
        else{                                    //if it doesn't have the value 'any'
            $('.group1:first').removeAttr('checked');//uncheck 1st box (ie 'any')
            $(this).attr('checked','checked');        //check the box being clicked
        }
    }
    
    if($('.group1').is(':checked')== false){    //if no boxes are checked
        $('.group1:first').attr('checked', true); //select 1st box (ie 'any')
    }
});
</skript>
Could anyone tell me how to make this work for multiple groups without repeating myself eg. a foreach loop??
#6

[eluser]cahva[/eluser]
Target the form's checkboxes in general and get the classname depending whats clicked and act accordingly. Easier to give you the code, check here:

http://jsbin.com/omexa4/edit
#7

[eluser]umbongo[/eluser]
Thanks, sorted. Very useful to a jquery noob!




Theme © iAndrew 2016 - Forum software by © MyBB