Limit number of checkboxes allowed to be checked [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Count the number of checkboxes selected without reloading the page?
I have an order form that asks the User which type of pass they would like (1-3 days), and gives them the option to choose the days they want the pass for.
Currently, when they choose 3 days, my JQuery selects all 3 checkboxes for them, and deselects when they choose 1 or 2 day(s). However, what I'm trying to do is:
When they select 2 day pass, it only allows them to check a maximum of 2 boxes. When they select a 1 day pass, it only allows them to check 1 box.
I'm drawing a blank as to what needs to go in my validateDays() function - the best way to go about running this validation or whether this is actually the best route to take.
Every method I think of using requires the checkboxes to have the same Name/ID - but due to other parts of the form (omitted), they unfortunately can't.
Any ideas / pointers?
HEAD Section JavaScript:
<script type="text/javascript">
function validateDays() {
$('#matthewpeckham').find('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('#matthewpeckham').find('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
else {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', false);
}
})
$('input[name="other_1"]').change(function () {
$('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery('#3daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
});
jQuery('#2daypass , #1daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
});
});
</script>
BODY Section HTML:
<input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="validateDays();">
<input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">

Here's a jQuery solution: jsFiddle example
$('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
})
$('input[name="other_1"]').change(function () {
$('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});

You need to check the number of checked boxes in your validate function:
function validateDays() {
var numBoxesChecked = $("input:checkbox:checked").length;
if (document.getElementById("2daypass").checked && numBoxesChecked > 2) {
// invalid
}
if (document.getElementById("1daypass").checked && numBoxesChecked > 1) {
// invalid
}
}
Keep in mind that any javascript validation can be bypassed, so ensure you are performing some type of validation on your server as well.
Also note you may want to change the numBoxesChecked selector if there are other unrelated checkboxes on the page, such as limiting it to a container e.g.
var numBoxesChecked = $('#someContainer').find("input:checkbox:checked").length;

jQuery exposes a checkbox selector that should prove useful here.
Your validateDays function can then do something along these lines
var checkedBoxes = jQuery(":checkbox:checked");
var numChecked = checkedBoxes.length;
...
else if (document.getElementById("2daypass").checked) {
if (numChecked > 2) { /*do something*/ }
}
else if (document.getElementById("1daypass").checked) {
if (numChecked > 1) { /*do something*/ }
}
else {
// DO NOTHING
}
...
However, you might have an issue with "reverting" the box. You might be able to do simply
jQuery(this).prop('checked', false)

I'm not an expert in this area by any means but here is what I do on a site of mine, you should be able to modify it to suit your needs...just remember to give your inputs the same class name.
<script type="text/javascript">
function Check() {
var count = 0;
var checkBoxes = document.getElementsByClassName('chkValidation');
for (var index = 0; index < checkBoxes.length; index++) {
if (checkBoxes[index].type == 'checkbox') {
if (!checkBoxes[index].disabled) {
count = checkBoxes[index].checked ? (count + 1) : count;
}
}
}
if (count > 3) {
alert('Question two - please select a maximum of 3 sub questions to ask.');
return false;
}
return true;
}

You could also do it dymanically, using a function like so:
$('.checkbox').on('click', function(e) {
var num_checked = 0;
$('.checkbox').each(function() {
if ( $(this).prop('checked') ) num_checked++;
});
var max_checked = $('input[name="other_1"]:checked').val();
if ( num_checked > max_checked ) {
$(this).prop('checked', false);
}
});
Assuming a few small modifications to your html:
<input name="other_1" type="radio" value="3" id="3daypass">
<input name="other_1" type="radio" value="2" id="2daypass">
<input name="other_1" type="radio" value="1" id="1daypass">
<input class="checkbox" name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input class="checkbox" name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input class="checkbox" name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">
Demo: http://jsbin.com/osecep/1/
It's not perfect, and you'd probably want to clear the checkboxes when the number of days is changed, but that should set you on the right track.

Related

Is there a javascript function that I can make to give radiobuttons a value?

So I have a small issue with getting some values on radiobuttons. I've made a foreach loop in where the html makes radiobuttons. These are Yes/No buttons and Each yes/no set needs a value.
Like question 1 will have value 1, 2 will have 2, 3 will have 4, 4 will have 8 etc.
In the end it needs to add up to a total score, BUT if NO is selected (eg. question 4 with value of 8 is NO, then the value becomes 0)
Ive tried doing a Javascript function shown below that makes it sort of work. But if all answers are NO and you make question 4 YES(which should have a value of 8) then it just says that my value is 2. I knew that this wouldnt work but I'm wondering if I can change this in a way that I can make it work the way that I want to
#foreach (var item in Model)
{
<div class="box">
<p>#Html.DisplayFor(modelItem => item.Question)</p>
<label>
<input id="yes" type="radio" name="#item.Id" checked="">
<span class=" yes randobtn">Ja</span>
</label>
<label>
<input id="no" type="radio" name="#item.Id">
<span class="no randobtn">Nee</span>
</label>
</div>
}
<button class="btn btn-primary" onclick="GetCount()">check</button>
#section Scripts{
<script type="text/javascript">
$(document).on('click',
'#btn',
function() {
console.log('test');
location.href = "/Symptom/GetProblems?TotalPoints=" +
count;
});
var count = 1;
$(document).on('click',
'.randobtn',
function() {
GetCount();
});
function GetCount() {
var checkedRadioBtns = $('input[type="radio"]:checked');
count = 1;
for (var i = 0; i < checkedRadioBtns.length; i++) {
if (checkedRadioBtns[i].id === 'no') {
console.log('in de if');
continue;
} else {
count = count * 2;
}
}
alert(count);
}
</script>
}
This is what I want: http://prntscr.com/o6zrqd
But as you can see in the alert it just says 1 when NO is selected
put value of true and false in the array
and then
value="#item.true_value"

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

How to check checkbox checked or not using javascript?

How to check checkbox checked or not using javascript ?
I have a lot of checkbox (dynamic data) . I want to know how can i check when checked chekcbox >= '1' using javascript ?
<input type="checkbox" id="1" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="2" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="3" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="4" name="test[]" onclick="test_fn()"/>
<script>
function test_fn() {
// check it's have checked checkbox or not ? //
}
</script>
Try to pass this in your inline handler,
<input type="checkbox" id="1" name="test[]" onclick="test_fn(this)"/>
And use this.checked to find out whether it is checked or not,
function test_fn(elem) {
alert(elem.checked);
}
DEMO
To check, if the the checked check box greater than or equal to 1, then just do
function test_fn(elem) {
if (document.querySelectorAll("input[name='test[]']:checked").length >= 1) {
alert("yes it is greater than or equal to 1")
}
}
DEMO
function test_fn()
{
if (this.checked) return true;
else return false;
}
Edit:
this reference won't work in this case, thanks to #RajaprabhuAravindasamy for pointing this out, read the comments or check this SO question for more information.
You need to pass a reference explicitly to the checkbox element:
function test_fn (el)
{
if (el.checked) return true;
else return false;
}
As for how to know if checked boxes count is more than one you can simply use a global variable to keep a track of the count like this:
var count = 0;
function test_fn (el)
{
el.checked ? count++ : count--;
return count > 1;
// if (count > 1) alert ("count is more than 1");
}
Demo

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Categories

Resources