You are viewing limited content. For full access, please sign in.

Question

Question

Limit Checkbox selection number

asked on June 29, 2016 Show version history

Hi,

I have a form with 8 check-boxes. I need to limit the users to only choose 2 checkbox before submitting the form. Is there there anyway to accomplish this with javascript? 

Thanks, Mary

0 0

Answer

APPROVED ANSWER
replied on June 30, 2016

Hi Mary,

Try adding this to the Javascript on your Form:

function readInput(input) {
  var i = 0;
  $(".checkboxes input").each(function(){
    if ($(this).prop("checked")) {
      i++;
    }
  });
  if (i > 2) {
    alert("You may only pick 2 options");
    $("#"+input.data.id).prop("checked", false);
  }
}

$(document).ready(function(){
  $(".checkboxes input").each(function(){
    $(this).on("click", {id:$(this).attr("id")}, readInput);
  });
});

Also for this to work you'll need to add a class called "checkboxes" to the checkboxes you need to validate on your form.

I hope this helps!

Cheers, Dan

2 0
replied on June 30, 2016

works perfectly.

0 0
replied on September 25, 2019 Show version history

I am very much a beginner to javascript and I can't figure out what I need to change to make this work for us... I added this (with the CSS class checkbox as recommended):

And tried playing around with the javascript in any way I could think of that might help (like adding in the question ID) but I couldn't seem to get it to work...

My understanding of javascript is exceptionally rudimentary so I really don't know where to go from here... Thoughts?

Replies

replied on October 11, 2024

This solution doesn't work any longer. What has changed since 2016?

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.