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
Related
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>
I have Vue data;
Like as app.$data.Result this result coming from server and it is just value(0-31) ;
I want to arrange my checkboxes with depend on this value;
This is checkboxes;
<div class="form-group">
<input class="checkbox" data-role="checkbox" data-caption="Issue1" id="ch1" value="1" />
<input class="checkbox" data-role="checkbox" data-caption="Issue2" id="ch2" value="2">
<input class="checkbox" data-role="checkbox" data-caption="Issue3" id="ch3" value="4" >
<input class="checkbox" data-role="checkbox" data-caption="Issue4" id="ch4" value="8">
<input class="checkbox" data-role="checkbox" data-caption="Issue5" id="ch5" value="16" >
</div>
I can set them by coming data with their using Id's
if (app.$data.Result == 1) {
$("#ch1").prop("checked", true);
}
But this way is too long because app.$data.Result can be like "3" and i must checked Issue1 and Issue2 also when User click any checkbox ,i need add/sub app.$data.Result so how can i solve this problem with Vue.
give you an example:
code updated,and the checkbox will be checked in 3 seconds
var app = new Vue({
el: '#app',
data () {
return {
list: new Array(5).fill('').map((o,i)=>i),
checked:[]
}
},
created () {
setTimeout(_=>{
//receive your data here
this.checked = [1,3]
},3000)
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<label v-for="i in list"><input type="checkbox" :value="i" v-model="checked">{{i}}</label>
{{checked}}
</div>
I implement like this and work but i am not sure that is clear solution;
<div class="form-group">
<input class="checkbox" data-role="checkbox" data-caption="Issue1" value="1" :checked="(data.Result& 1) === 1" />
<input class="checkbox" data-role="checkbox" data-caption="Issue2" value="2" :checked="(data.Result& 2) === 2">
<input class="checkbox" data-role="checkbox" data-caption="Issue3" value="4" :checked="(data.Result& 4) === 4" >
<input class="checkbox" data-role="checkbox" data-caption="Issue4" value="8" :checked="(data.Result& 8) === 8">
<input class="checkbox" data-role="checkbox" data-caption="Issue5" value="16" :checked="(data.Result& 16) === 16">
</div>
And when user change checkbox,result will be change and i handle it like this;
var sum = 0;
$("input:checked").each(function() {
sum += parseInt($(this).val(), 10);
});
data.Result = sum;
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);
}
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!");
}
});
});
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