Get only two values of multiple Checkboxes - javascript

I found this code on codeLAB and I'm trying to get true result only if "Cricket" and "Boxing" are checked. Currently it works if both of them are checked, but also when the others are selected.
https://jsfiddle.net/kubus1234/oksm8eaw/
$("button").click(function() {
var favorite = [];
$.each($("input[name='sport']:checked"), function() {
favorite.push($(this).val());
});
var test = [];
$.each($("input[name='sport']:checked"), function() {
test.push($(this).val());
});
if (favorite[1] == "cricket" || test[1] == "boxing") {
alert("Your are the best");
} else {
alert("Your are looser");
}
});
Any solution?

Not sure why you traversed the selected checkboxes twice, but here's one way to get your results:
$(document).ready(function() {
$("button").click(function() {
var selected = $("input[name='sport']:checked").toArray().map(function(checkbox) {
return $(checkbox).val();
});
if (selected.length === 2 && selected[0] === "cricket" && selected[1] === "boxing") {
alert("You are the best");
} else {
alert("You lose");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h3>Select your favorite sports:</h3>
<label>
<input type="checkbox" value="football" name="sport">Football</label>
<label>
<input type="checkbox" value="baseball" name="sport">Baseball</label>
<label>
<input type="checkbox" value="cricket" name="sport">Cricket</label>
<label>
<input type="checkbox" value="boxing" name="sport">Boxing</label>
<label>
<input type="checkbox" value="racing" name="sport">Racing</label>
<label>
<input type="checkbox" value="swimming" name="sport">Swimming</label>
<br>
<button type="button">Get Values</button>
</form>

This would be easily researchable but I'll post a solution anyway
1) I gave the checkboxes ids
2) I changed the JavaScript to check if both checkboxes are checked at once with .is(":checked")
<form>
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" id="chkFootball" value="football" name="sport"> Football</label>
<label><input type="checkbox" id="chkBaseball" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" id="chkCricket" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" id="chkBoxing" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" id="chkRacing" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" id="chkSwimming" value="swimming" name="sport"> Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
$(document).ready(function() {
$("button").click(function(){
if ($('#chkCricket').is(':checked') && $('#chkBoxing').is(':checked')) {
alert("Checked");
}
else {
alert("Not checked");
}
});
});

https://jsfiddle.net/oksm8eaw/2/
Please don't use javascript alerts. Alerts cause cancer...
... instead use ids, and jQuery html(): add this to the HTML: <div id="result"></div>
Solution
$(document).ready(function() {
$("button").click(function(){
var matchCount = 0;
$('input').each(function(){
if( this.value == "cricket" || this.value == "boxing") {
if(this.checked) matchCount++;
}
});
if(matchCount>1){
$("#result").html("YUP!");
} else {
$("#result").html("NOPE!");
}
});
});

Related

Want to get the value of checkbox and assign it's value to the class-name

In a div, I have a 'select all' checkbox. When this checkbox is checked, all the other checkboxes will automatically checked. I want to assign their values as a class name. I am able to achieve this when a single checkbox is checked. But now I want this should work when all checkbox is checked at once when a select-all checkbox is checked. ​
$('.select-all').on('click', function() {
let isSelected = $(this).is(':checked');
$(this).parents('.checkbox-list').find('input[type="checkbox"]').not('.select-all').each(function() {
if (isSelected) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
})
});
$('input:checkbox').not('.select-all').change(function() {
var cl = $(this).val();
var cls = 'abc' + '' + cl + '';
if ($(this).is(':checked')) {
$(this).addClass(cls);
} else {
$(this).removeClass(cls);
}
})
<div class="checkbox-list">
<label><input type="checkbox" class="select-all" name="">All</label>
<label><input type="checkbox" name="" value="1">One</label>
<label><input type="checkbox" name="" value="2">Two</label>
<label><input type="checkbox" name="" value="3">Three</label>
<label><input type="checkbox" name="" value="4">Four</label>
<label><input type="checkbox" name="" value="5">Five</label>
<label><input type="checkbox" name="" value="6">Six</label>
<label><input type="checkbox" name="" value="6">Three</label>
<label><input type="checkbox" name="" value="7">Four</label>
<label><input type="checkbox" name="" value="8">Five</label>
<label><input type="checkbox" name="" value="9">Six</label>
</div>
You pretty much wrote the code already to achieve this,
What i did here is adding the cl = $(this).val(); and cls = 'abc' + '' + cl + ''; in the each loop and add the class when isSelected is true, and delete when false.
$('.select-all').on('click', function() {
let isSelected = $(this).is(':checked');
$(this).parents('.checkbox-list').find('input[type="checkbox"]').not('.select-all').each(function() {
let cl = $(this).val();
let cls = 'abc' + '' + cl + '';
if (isSelected) {
$(this).prop('checked', true);
$(this).addClass(cls);
} else {
$(this).prop('checked', false);
$(this).removeClass(cls);
}
})
});
$('input:checkbox').not('.select-all').change(function() {
let cl = $(this).val();
let cls = 'abc' + '' + cl + '';
if ($(this).is(':checked')) {
$(this).addClass(cls);
} else {
$(this).removeClass(cls);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox-list">
<label><input type="checkbox" class="select-all" name="">All</label>
<label><input type="checkbox" name="" value="1">One</label>
<label><input type="checkbox" name="" value="2">Two</label>
<label><input type="checkbox" name="" value="3">Three</label>
<label><input type="checkbox" name="" value="4">Four</label>
<label><input type="checkbox" name="" value="5">Five</label>
<label><input type="checkbox" name="" value="6">Six</label>
<label><input type="checkbox" name="" value="6">Three</label>
<label><input type="checkbox" name="" value="7">Four</label>
<label><input type="checkbox" name="" value="8">Five</label>
<label><input type="checkbox" name="" value="9">Six</label>
</div>

Disable a specific checkbox using Javascript

I would like to request assistance on how can I disable a specific checkbox.
Scenario:
If I clicked the 'Yes to all' checkbox - the other checkbox will be disabled (Q1 to Q4)
If I selected one or more on the Q1 to Q4 checkbox - 'Yes to all' checkbox will be disabled
Code:
$('input[type=checkbox]').change(function() {
if ($(this).is(':checked')) {
$('input[type=checkbox]').attr('disabled', true);
$(this).attr('disabled', '');
} else {
$('input[type=checkbox]').attr('disabled', '');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You need to check weather the checkboxes selected or not as per your requirement,
Condition 1: if question selected length is more than 1, then disable the YTA
condition 2: if YTA is selected then disable all the Questions
If need anything else, please let me know.
$('.yta').change(function() {
if($('.yta:checked').length){
$('.q').attr('disabled', true);
}else {
$('.q').removeAttr("disabled");
}
});
$('.q').change(function() {
if($('.q:checked').length){
$('.yta').attr('disabled', true);
}else {
$('.yta').removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q" type="checkbox" name="Q1" value="1" />Q1
<input class="q" type="checkbox" name="Q2" value="2" />Q2
<input class="q" type="checkbox" name="Q3" value="3" />Q3
<input class="q" type="checkbox" name="Q4" value="4" />Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA" />Yes to all
My answer with my philosophy:
Avoid jQuery if you can
Use small functions that do one thing
Have in mind that the same should work when used multiple times in a document
Prevent magic values in your code
Encapsulate as much as possible
So this seems like overkill, but this works
{
function checkAnswers(qNames, allName) {
const qSelector = qNames.map(e => `[name="${e}"]`).join(',')
const allSelector = `[name="${allName}"]`
const selector = `${qSelector},${allSelector}`;
const getValue = () => Array.from(document.querySelectorAll(selector)).filter(e => e.checked).map(e => ({[e.name]: e.value}))
const checkQ = value => value.map(e => Object.keys(e)[0]).filter(value => qNames.includes(value)).length > 0;
const checkAll = value => value.map(e => Object.keys(e)[0]).includes(allName)
const qDisable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = true)
const qEnable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = false)
const allDisable =() => document.querySelector(allSelector).disabled = true
const allEnable = () => document.querySelector(allSelector).disabled = false
return e => {
if (!e.target.closest(selector)) {return}
const value = getValue();
if (checkQ(value)) {
allDisable();
} else if (checkAll(value)) {
qDisable()
} else {
allEnable();
qEnable();
}
}
}
let qNames = ['QA1','QA2','QA3','QA4']
let allName = 'QAYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
qNames = ['QB1','QB2','QB3','QB4']
allName = 'QBYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
}
:disabled + label {
color: lightgray;
}
<input type="checkbox" id="QA1" name="QA1" value="1"/><label for="QA1">Question 1</label><br>
<input type="checkbox" id="QA2" name="QA2" value="2"/><label for="QA2">Question 2</label><br>
<input type="checkbox" id="QA3" name="QA3" value="3"/><label for="QA3">Question 3</label><br>
<input type="checkbox" id="QA4" name="QA4" value="4"/><label for="QA4">Question 4</label><br>
<input type="checkbox" id="QAYTA" name="QAYTA" value="YTA"/><label for="QAYTA">Yes to all</label>
<br><br>
<input type="checkbox" id="QB1" name="QB1" value="1"/><label for="QB1">Question 1</label><br>
<input type="checkbox" id="QB2" name="QB2" value="2"/><label for="QB2">Question 2</label><br>
<input type="checkbox" id="QB3" name="QB3" value="3"/><label for="QB3">Question 3</label><br>
<input type="checkbox" id="QB4" name="QB4" value="4"/><label for="QB4">Question 4</label><br>
<input type="checkbox" id="QBYTA" name="QBYTA" value="YTA"/><label for="QBYTA">Yes to all</label>
You can do something like this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q1_q4" type="checkbox" name="Q1" value="1"/>Q1
<input class="q1_q4" type="checkbox" name="Q2" value="2"/>Q2
<input class="q1_q4" type="checkbox" name="Q3" value="3"/>Q3
<input class="q1_q4" type="checkbox" name="Q4" value="4"/>Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA"/>Yes to all
<script>
$(".q1_q4").on('change', function(){
$(".yta").attr("disabled","disabled");
});
$(".yta").on('change', function(){
$(".q1_q4").attr("disabled","disabled");
});
</script>
See the perfect answer.
$('input[type=checkbox]').change(function() {
if ($(this).is('input[name="QYTA"]')) {
if ($(this).is(':checked')) {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', true);
} else {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', false);
}
} else {
if ($(this).is(':checked')) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', true);
} else if($('input[type=checkbox][name!="QYTA"]:checked').length == 0) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', false);
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You can use the .prop function in jQuery to add and remove the disabled attribute easily. You would need to refine the selectors if you are using other checkboxes on the same page.
$('input[type=checkbox]').change(function() {
if (this.name == "QYTA" && this.checked) {
$('input[type=checkbox][name!="QYTA"]').prop("disabled", true);
} else if (this.name != "QYTA" && this.checked) {
$('input[type=checkbox][name="QYTA"]').prop("disabled", true);
} else {
$('input[type=checkbox]').prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
My solution is to set up onchange event handler for each checkbox.
And then depending on the element which triggered the onchange event to perform a different operation.
if QYTA trigger the onchange then disable the Q1 to Q4 checkbox.
Else
disable the QYTA checkbox.
I make use of the logic difference between the checked and disabled attribute.
Here is my solution:
$("input[type='checkbox']").each(function() {
$(this).on('change', function() {
if (this.name=='QYTA'){
for (let i=1;i<5;i++){
$("input[type='checkbox'][name='Q"+i+"']").attr('disabled', this.checked);
}
} else{
$("input[type='checkbox'][name='QYTA']").attr('disabled', this.checked);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all
hope help u
$("input[type='checkbox']").each(function(){
$(this).on('click', function(){
var el = $("input[type='checkbox']").not($("input[name='QYTA']"));
var elAl = $("input[name='QYTA']");
if($(this).not(elAl).length == 0) {
if(elAl.is(':checked')){
el.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
} else if(el.is(':checked')){
elAl.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all

How set checked checkbox if it's value is in array

I have inputs:
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
And my javascript:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray($(this).val(), initValues)));
});
And now all my checkboxes are checked. How must I change my code to set checked for ckeckboxes which values are in initValues array?
$.inArray returns the index, not boolean. Also, parseInt your value because its considered as string when you pick it up.
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", $.inArray(parseInt($(this).val()), initValues) == -1 ? false : true );
});
let initValues = [1, 2, 3];
$('#my').find(':checkbox[name="names[]"]').each(function() {
if (initValues.some(v => v == $(this).val())) {
$(this).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
You need to turn the value back into a number so it compares with the array value.
$.inArray(+$(this).val(), initValues))
Revised Example:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray(+$(this).val(), initValues)) != -1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
function printChecked(isChecked, value) {
const newProjectStages = projectstage.filter((p) => p !== value);
if (isChecked) {
newProjectStages.push(value);
}
Setprojectstage(newProjectStages);
var items = document.getElementsByName("tr");
var selectedItems = [];
for (var i = 0; i < items.length; i++) {
if (items[i].type == "checkbox" && items[i].checked == true)
selectedItems.push(items[i].value);
}
console.log("selected val", selectedItems);
Setselectedprostages(selectedItems);
}

How to limit the number of checked checkbox in jQuery? [duplicate]

I have the following HTML:
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>
Live site:
http://www.chineselearnonline.com/amember/signup20.php
How can I do it so that the user can only select 3 of those checkboxes?
Using change event you can do something like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
See this working demo
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
$('.checkbox').click(function(){
if ($('.checkbox:checked').length >= 3) {
$(".checkbox").not(":checked").attr("disabled",true);
}
else
$(".checkbox").not(":checked").removeAttr('disabled');
});
i used this.
I think we should use click instead change
Working DEMO
$("input:checkbox").click(function(){
if ($("input:checkbox:checked").length > 3){
return false;
}
});
Working DEMO
Try this
var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
theCheckboxes.click(function()
{
if (theCheckboxes.filter(":checked").length > 3)
$(this).removeAttr("checked");
});
I'd say like letiagoalves said, but you might have more than one checkbox question in your form, so I'd recommend to do like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
(function ($) {
$(document).ready(function () {
$(document).on("change", ".pricing-levels-3 input", function () {
var numberOfChecked = $(".pricing-levels-3 input:checkbox:checked").length;
if (numberOfChecked >= 2) {
$(".pricing-levels-3 input:not(:checked)").prop("disabled", true);
} else {
$(".pricing-levels-3 input:not(:checked)").removeAttr("disabled", true);
}
});
});
})(jQuery);
This is working for me with checkbox name.
<script>
// limit checkbox select
$('input[name=vehicle]').on('change', function (e) {
if ($('input[name=vehicle]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
</script>
This is how I made it work:
// Function to check and disable checkbox
function limit_checked( element, size ) {
var bol = $( element + ':checked').length >= size;
$(element).not(':checked').attr('disabled',bol);
}
// List of checkbox groups to check
var check_elements = [
{ id: '.group1 input[type=checkbox]', size: 2 },
{ id: '.group2 input[type=checkbox]', size: 3 },
];
// Run function for each group in list
$(check_elements).each( function(index, element) {
// Limit checked on window load
$(window).load( function() {
limit_checked( element.id, element.size );
})
// Limit checked on click
$(element.id).click(function() {
limit_checked( element.id, element.size );
});
});
I have Alter this function to auto uncheck previous
var limit = 3;
$('.compare_items').on('click', function(evt) {
index = $(this).parent('td').parent('tr').index();
if ($('.compare_items:checked').length >= limit) {
$('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');
//this.checked = false;
}
localStorage.setItem('last-checked-item', index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="compare_items">1
<input type="checkbox" class="compare_items">2
<input type="checkbox" class="compare_items">3
<input type="checkbox" class="compare_items">4
<input type="checkbox" class="compare_items">5
<input type="checkbox" class="compare_items">6
<input type="checkbox" class="compare_items">7
<input type="checkbox" class="compare_items">8
<input type="checkbox" class="compare_items">9
<input type="checkbox" class="compare_items">10
I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:
let maxCheckedArray = [];
let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
assessmentOptions.on('change', function() {
let checked = jQuery(this).prop('checked');
if(checked) {
maxCheckedArray.push(jQuery(this));
}
if(maxCheckedArray.length >= 3) {
let old_item = maxCheckedArray.shift();
old_item.prop('checked', false);
}
});
This method works well with checkboxes in a container, such as bootstrap checkbox
const checkedLimmit = 2;
function ValidateCheckBoxGroup(container) {
if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
} else {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
}
}
$(function () {
// validate containers on page load
$('div.checkbox-group').each(function () {
ValidateCheckBoxGroup($(this));
});
// set checkbox events
$('div.checkbox-group input[type="checkbox"]').change(function () {
ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
});
});
JS and HTML
This worked for me what it does is that, the onclick function checkControl() will count the number of times the checkbox has been clicked then if it's greater than 3 display error message.
function checkboxControl(j) {
var total = 0;
var elem = document.getElementsByClassName("checkbox");
var error = document.getElementById("error");
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked == true) {
total = total + 1;
}
if (total > 3) {
error.textContent = "You Must Select at Least 3";
elem[j].checked = false;
return false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="">
<span id="error" style="color: red"></span>
<br>
<span>Python</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(0)"
id="1"
/>
<br>
<span>Javascript</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(1)"
id="1"
/><br>
<span>Go</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(2)"
id="1"
/><br>
<span>Laravel</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(3)"
id="1"
/>
</form>
</body>
</html>
This resources helped me understand
https://www.plus2net.com/javascript_tutorial/checkbox-limit-demo2.php
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
This function simply checks if you have just checked a checkbox. If yes, it increments the checked value by one. If it reaches the limit then the next checkbox is rejected.
var limit = 3;
var checked = 0;
$('.single-checkbox').on('change', function() {
if($(this).is(':checked'))
checked = checked+1;
if($(this).is(':checked') == false)
checked = checked-1;
if(checked > limit) {
this.checked = false;
checked = limit;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>

Alert when selected similar value from multiple check box with the same class name

When I select for a second time from the below check box with the same value it should alert 'value is already checked' How do I do that using jquery?
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="2"/>
</div>
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
<div>
<input type="checkbox" class="check" value="4"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
I tried with below code but nothing is working
var itemVal=false;
$(document).on('change','.check:checked',function(){
selVal=$(this).val();
$('.check:checked').each(function(){
if($(this).val()==selVal)
itemVal=true;
});
if(itemVal==true){
alert('Proceed');
}else{
alert('Please choose same name');
}
});
Try this:
$('.check').change(function(event){
var arr = $(".check:checked").map(function() {
return $(this).val();
}).get();
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
if(results.length >0){
alert('value is already checked')
}
});
Demo:
http://jsfiddle.net/9a8o37h0/1/
Like this:
$('.check').click(function () {
if(!this.checked)
alert("Value is already Checked");
});
If you want to keep it checked add this before the alert
this.checked = true;

Categories

Resources