Jquery CheckBox Selection/Deselection optimally given X checkboxes

Posted by Amitd on Stack Overflow See other posts from Stack Overflow or by Amitd
Published on 2010-04-02T10:27:14Z Indexed on 2010/04/02 10:33 UTC
Read the original article Hit count: 375

Filed under:
|
|

Hi guys,

I have suppose say 'X' check-boxes(any input elements) in a Form and "M" option selection indexes ("M" less than equal to "X"). then how do i select the "M" option indexes/values and deselect the rest of check-boxes optimally?

i.e.Suppose I have 10 Checkboxes and 5 Option Indices(eg: 1,2,4,5,8) then i have to select checkboxes with given index .

I could come up with the following code:

   HTML:

     <div id="Options">     
        <input id="choice_1"  type="checkbox" name="choice_1" value="Option1"><label for="choice_1">Option1</label>
        <input id="choice_2"  type="checkbox" name="choice_2" value="Option2"><label for="choice_2">Option2</label>
        <input id="choice_3"  type="checkbox" name="choice_3" value="Option3"><label for="choice_3">Option3</label>    

    ..
    ..till choice_10

     </div>

    IN JS:

   //Have to select checkboxes with "Value" in choicesToSelect and give a selection   
  //effect to its label
    var choicesToSelect={"Option1","Option9","Option3","Option4","Option2"};
    selectHighlightCheckBoxes(choicesToSelect);


    function selectHighlightCheckBoxes(choices){
     $.each(
                                choices, function(intIndex, objValue) {

//select based on id or value or some criteria
                                    var option = $("#Options :input[value=" + objValue + "]") ;                       
                                    if ($(option).is("input[type='radio']") || $(option).is("input[type='checkbox']")) {
                                        $(option).attr('checked', true);
                                        $(option).next('label:first').css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' });
                                    } else if ($(option).is("input[type='text']")) {
                                        $(option).css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' });
                                    } else {

                                    }
                                }
                         );
   }

But i want to also add effect to the rest (not in choicesToSelect array) also. (may be red color to those not in choiceToSelect) Can this be done in the one traversal/loop? Optimally? or Better way?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html