"If" statements how to check out if multiple checkboxes is checked after a button click?

Viewed 249

I have a button and 3 checkboxes, after button click I want to show a message if one or more of these checkboxs is checked. I prefer Jquery code if it's possible. Thanks and any assistance it would be greatly appreciated.

$(function() {
  $(".btn").click(function() {
    if ($('input[type="checkbox"]').is(":checked")) {
      if ($('input[name="box-1"]').is(":checked")) {
        $(".message").text("Box-1 is checked");
      }
      if ($('input[name="box-2"]').is(":checked")) {
        $(".message").text("Box-2 is checked");
      }
      if ($('input[name="box-3"]').is(":checked")) {
        $(".message").text("Box-3 is checked");
      }
    } else {
      $(".message").text("No box is checked");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="box-1">
<input type="checkbox" name="box-2">
<input type="checkbox" name="box-3">

<p class="message"></p>
<button class="btn">CLICK ME</button>

My code works fine, but the problem is the message shows only one checkbox is checked and I want to show for example: If box-1 and box-3 are checked, message will be "box-1 and box-3 are cheched" and the same way with other checkboxes. Thanks and any assistance it would be greatly appreciated.

4 Answers

Check the length of how many checkboxes are checked? And use .map() this way:

$(function() {
  $(".btn").click(function() {
    if ($('input[type="checkbox"]:checked').length > 0) {
      $(".message").text("Success! You have checked " + [...$('input[type="checkbox"]:checked').map(function () {
        return this.name;
      })].join(", ") + ".");
    } else {
      $(".message").text("Sorry! You should check at least 3 checkboxes!");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="box-1" />
<input type="checkbox" name="box-2" />
<input type="checkbox" name="box-3" />

<p class="message"></p>
<button class="btn">CLICK ME</button>

What does .map() function do?

.map() Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

Preview

Can you check this preview?

First find all of the checked boxes, then join them together with and, the check if there are spaces, if so, then add "are" for plural, if not then add "is" for singular, then if there is an output, add "checked." to it. Finally, if output exists, set the textbox to it, if not, then return "No box is checked".

$(function() {
  $(".btn").click(function() {
    let output = [...$('input[type="checkbox"]:checked')].reduce((acc, _, ind) => acc ? (acc + ` and Box-${ind+1}`) : `Box-${ind+1}`, "");
    if (output.split` `.length>1) output += " are ";
    else if (output) output += " is ";
    if (output) output += "checked."
    
    $(".message").text(output || "No box is checked");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="box-1">
<input type="checkbox" name="box-2">
<input type="checkbox" name="box-3">

<p class="message"></p>
<button class="btn">CLICK ME</button>

The problem is even if multiple boxes are checked, the .text() method will default to the last if conditional where is(":checked") equals true always overwriting any previous cases that were also true.

What I would recommend is creating a variable to store the message you want to output, then concatenate onto it for each if check that is true. I imagine you want line breaks between each output, so just put <br> at the end of each line. Lastly, use .html() method to set the .message element instead of .text().

$(function() {
  $(".btn").click(function() {
    if ($('input[type="checkbox"]').is(":checked")) {
      //create message variable to hold html to be inserted
      var message = "";

      if ($('input[name="box-1"]').is(":checked")) {
        message += "Box-1 is checked<br>";
      }

      if ($('input[name="box-2"]').is(":checked")) {
        message += "Box-2 is checked<br>";
      }

      if ($('input[name="box-3"]').is(":checked")) {
        message += "Box-3 is checked<br>";
      }

      //set using '.html()' instead of '.text()' so you can insert breaks yourself
      $(".message").html(message);
    } else {
      $(".message").text("No box is checked");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="box-1">
<input type="checkbox" name="box-2">
<input type="checkbox" name="box-3">

<p class="message"></p>
<button class="btn">CLICK ME</button>

    $(function() {
      const mapNameToText = {
        'box-1': 'Box-1',
        'box-2': 'Box-2',
        'box-3': 'Box-3',
      }

      let checkedBoxes = [];

      $(".btn").click(function() {
        checkedBoxes = [];

        $.each(mapNameToText, (key, value) => {
          if($('input[name=' + key + ']').is(":checked")) {
            checkedBoxes.push(value);
          }
        });

        if(checkedBoxes.length) {
          $(".message").text(`${checkedBoxes.join(', ')} ${checkedBoxes.length > 1 ? 'are' : 'is'} checked`);
        } else {
          $(".message").text("No box is checked");
        }
      });
    });
Related