Javascript: How to check only one item in checkbox - javascript

Please help, I failed to code the checkbox that can only checked 1 item. Any help would be appreciated. Thanks
Html
<input type="checkbox" name="<%=Name %>" onClick="return checkbox(this)" >
Javascript
function checkbox(a) {
var Count = 0;
if (a.checked)
{
Count = Count + 1;
}
if (Count == 2)
{
alert('choose One Please');
return false;
}
}

You are declaring count inside a method hence it will always be initialised to 0 when you click on check box. Hence declare count globally and maintain the count.
var NewCount = 0;// global declaration
function KeepCount(a){
if (a.checked){
NewCount = NewCount + 1;
}else{
NewCount = NewCount - 1;
}
if(NewCount>1){
alert('Pick Just One Please');
return false;
}
}
UPDATE:
Another approach if you don't want to add variable globally:
HTML
Group 1
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<br/>
Group 2
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
JavaScript
function addClassCheck(element){
if(element.checked){
element.classList.add("marked");
}else{
element.classList.remove("marked");
}
if(document.getElementsByClassName("marked").length>1){
alert("Please select only one check box");
element.checked=false;
element.classList.remove("marked");
}
}
Fiddle demo

Group your checkboxs as
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<br/>
Group 2
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
Query
$("input:checkbox").click(function() {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
DEMO

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 Validate Multiple radio buttons

How can I validate multiple radio buttons. All these radio buttons generated dynamically.
<input type="radio" name="answer_option1" value="1" id="ans_options1" />
<input type="radio" name="answer_option1" value="2" id="ans_options2" />
<input type="radio" name="answer_option1" value="3" id="ans_options3" />
<input type="radio" name="answer_option1" value="4" id="ans_options4" />
<input type="radio" name="answer_option2" value="5" id="ans_options5" />
<input type="radio" name="answer_option2" value="6" id="ans_options6" />
<input type="radio" name="answer_option2" value="7" id="ans_options7" />
<input type="radio" name="answer_option2" value="8" id="ans_options8" />
<input type="radio" name="answer_option3" value="9" id="ans_options9" />
<input type="radio" name="answer_option3" value="10" id="ans_options10" />
<input type="radio" name="answer_option3" value="11" id="ans_options11" />
<input type="radio" name="answer_option3" value="12" id="ans_options12" />
<input type="radio" name="answer_option4" value="13" id="ans_options13" />
<input type="radio" name="answer_option4" value="14" id="ans_options14" />
<input type="radio" name="answer_option4" value="15" id="ans_options15" />
<input type="radio" name="answer_option4" value="16" id="ans_options16" />
Try this http://jsfiddle.net/aamir/r9qR2/
Since each group has different name attribute so you have to do validation for each set of radio buttons.
if($('input[name="answer_option1"]:checked').length === 0) {
alert('Please select one option');
}
If you have unlimited number of groups. Try this http://jsfiddle.net/aamir/r9qR2/2/
//Make groups
var names = []
$('input:radio').each(function () {
var rname = $(this).attr('name');
if ($.inArray(rname, names) === -1) names.push(rname);
});
//do validation for each group
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length === 0) {
console.log('Please check ' + name);
}
});
If you want to show just 1 error for all groups. Try this http://jsfiddle.net/aamir/r9qR2/224/
try this new fiddle http://jsfiddle.net/Hgpa9/3/
$(document).on("click","#validate", function() {
var names = [];
$('input[type="radio"]').each(function() {
// Creates an array with the names of all the different checkbox group.
names[$(this).attr('name')] = true;
});
// Goes through all the names and make sure there's at least one checked.
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if (radio_buttons.filter(':checked').length == 0) {
alert('none checked in ' + name);
}
else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
}
}
});
var names = []
$('input[name^="answer_option"]').each(function() {
var rname = $(this).attr('name');
if ($.inArray(rname, names) == -1) names.push(rname);
});
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length == 0) {
console.log('Please check ' + name);
}
});

Javascript: Check Uncheck Grouped Checkboxes

I have a form like:-
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="modules[1]" onclick="checkgroup(this)" value="1">Module 1<br>
<input type="checkbox" name="units[1][1]">Unit 1
<input type="checkbox" name="units[1][2]">Unit 2
<input type="checkbox" name="units[1][3]">Unit 3<br>
<input type="checkbox" name="modules[2]" onclick="checkgroup(this)" value="2">Module 2<br>
<input type="checkbox" name="units[2][1]">Unit 4
<input type="checkbox" name="units[2][2]">Unit 5
<input type="checkbox" name="units[2][3]">Unit 6<br>
<input type="checkbox" name="modules[3]" onclick="checkgroup(this)" value="3">Module 3<br>
<input type="checkbox" name="units[3][1]">Unit 7
<input type="checkbox" name="units[3][2]">Unit 8
<input type="checkbox" name="units[3][3]">Unit 9
</form>
I want to check/uncheck all the sub checkboxes contained under each Module (Main Checkbox).
For example if i check "Module 1" then only Unit 1,2 and 3 should be checked and on uncheck of "Module 1" those Units should be unchecked. Same thing should behave for other modules.
I am looking for a Javascript function to perform this.
Try this
function checkgroup(obj){
var element = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++)
{
if(inputs[i].name.indexOf('units[' + obj.value + ']') == 0)
{
element.push(inputs[i]);
}
}
if(obj.checked){
for(i=0;i<element.length;i++){
element[i].checked = true;
}
}else{
for(i=0;i<element.length;i++){
element[i].checked = false;
}
}
}

Categories

Resources