最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Jquery Change background color of DIV to #333 only when all checkbox is not checked - Stack Overflow

matteradmin19PV0评论

I have 5 div with class .thumb-folder and inside each contains a checkbox. I also have another div with a class .alarm.

When 1 or many checkboxes is checked the div with .alarm class changes background to red.

How to change the div with the .alarm class to background #333 only when no checkboxes are checked?

Here is a link to jsfiddle of my current code.

I have 5 div with class .thumb-folder and inside each contains a checkbox. I also have another div with a class .alarm.

When 1 or many checkboxes is checked the div with .alarm class changes background to red.

How to change the div with the .alarm class to background #333 only when no checkboxes are checked?

Here is a link to jsfiddle of my current code.

Share Improve this question edited Jan 18, 2013 at 4:38 Mithun Satheesh 27.9k14 gold badges79 silver badges102 bronze badges asked Jan 18, 2013 at 4:28 guitarPHguitarPH 2012 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Use the sam eselector you used to bind the handler to check if any checkboxes are checked.

  $('.thumb-folder input:checkbox').on('click', function (e) {
      if ($('.thumb-folder input:checkbox').is(':checked')) {
        $('div.alarm').css("background-color","red");
      } 
    else{
        $('div.alarm').css("background-color","#333");
      }
  });

DEMO

You can use length to find the checked checkbox count using :checked

Live Demo

$('.thumb-folder input:checkbox').on('click', function (e) {
  if ($('.thumb-folder :checked').length == 0)
     $('div.alarm').css("background-color", "#333");
  else 
     $('div.alarm').css("background-color", "red");
});

You can just do this in 3 lines:

 $('.thumb-folder input:checkbox').on('click', function (e) {
        $('div.alarm').css("background-color",(($("input[type='checkbox']:checked").length > 0) ? "red" : "#333"));
  });
Post a comment

comment list (0)

  1. No comments so far