0

I have a HTML form and inside it I have a bunch of checkboxes.

What I am trying to do is this. - If any one checkbox is selected, I want to set a variavle in javascript. - if nothing is selected, I want to set that variable to blank. - I am toggling the class of the checkbox as well.

This is how I am currently doing it.

var checklist = "";
$('.form3 :checkbox').change(function() {           
    $(this).closest('label').toggleClass("checkselected", this.checked);
    if(window.checklist != "OL" )
    {
        window.checklist = "OL";
    }

});

The problem with this code is, if once the variable is set, I am not sure how to clear it is the user deselects all checkboxes and none of the boxes are selected any longer.

Any suggestion? (I am using jQuery)

3 Answers 3

2

you might wanna check the number of selected checkboxes.. that way, you would not have a problem. (Well, that is if "OL" does not mean anything...)

var checklist = "";
var checkboxes = $('.form3 :checkbox');
checkboxes.change(function() {           
    $(this).closest('label').toggleClass("checkselected", this.checked);
    checklist = checkboxes.filter(':checked').length;
    // checklist would then be 0 if none selected.
});
Sign up to request clarification or add additional context in comments.

Comments

0

To select all check boxes you can use

$('.form3 :checkbox").attr("checked", true);

To deselect

$('.form3 :checkbox").attr("checked", false); 

Comments

0

Following code is what you need:

<html>
<body>
  <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
  <style>
  .checkselected { color: red; }
  </style>
  <div class="form3">
    <label><input type="checkbox" />Option 1</label>
    <label><input type="checkbox" />Option 2</label>
    <label><input type="checkbox" />Option 3</label>
  </div>
  <script>
var checklist = "";
$('.form3 :checkbox').change(function() {           
    $(this).closest('label').toggleClass("checkselected", this.checked);
    if(window.checklist != "OL" )
    {
        window.checklist = "OL";
    }
    var size = $('.form3 :checkbox').length;
    var found = false;
    $('.form3 :checkbox').each(function(index) {
      if (this.checked) {
        found = true;
      }
      if (index == size - 1) {
        if (!found) {
          checklist = '';
        }
      }
    });
    alert(checklist);
});
  </script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.