开发者

Jquery Javascript checkbox selection/deselection

开发者 https://www.devze.com 2023-04-12 04:22 出处:网络
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.

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 dese开发者_JAVA百科lects all checkboxes and none of the boxes are selected any longer.

Any suggestion? (I am using jQuery)


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.
});


To select all check boxes you can use

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

To deselect

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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号