Uncheck a checkbox when another is checked - javascript

function uncheck() {
var notTest = document.getElementById("choice_31_3_2");
var Test = document.getElementById("choice_31_3_1");
if (notTest.checked) {
Test.checked = false;
}
if (Test.checked) {
notTest.checked = false;
}
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
I wrote a function to uncheck a checkbox if another one is checked, I am using jQuery to call uncheck() on those specific input.
I am getting the result I want. When I check test then check notTest, Test is being unchecked. BUT when I am pressing Test again, the test checkbox is refusing to check unless I manually uncheck notTest.
I included the code snippet , please can figure out what is wrong ?
The code is running normally on Wordpress but unfortunately not here.

Here you go with a solution
$('input[type="checkbox"]').change(function(){
console.log($(this).is(':checked'));
if($(this).is(':checked')){
$(this).siblings('input[type="checkbox"]').attr('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Hope this will help you.

You can code like this,
HTML:-
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
<input type="checkbox" class="example" />
JQUERY:-
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
Working Demo url
Hope this will help you.

BUT when i am pressing Test again, the test checkbox is refusing to
chech unless i manually uncheck notTest.
It is because when you press again, you didn't check which checkbox you have clicked on. You simply unchecked a checked-checkbox.
Try this simple approach
var allIds = [ "choice_31_3_1", "choice_31_3_2" ];
function uncheck( event )
{
var id = event.target.id;
allIds.forEach( function( id ){
if ( id != event.target.id )
{
document.getElementById( id ).checked = false;
}
});
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>

Try this.
$('input.test').on('change', function() {
$('input.test').not(this).prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="input_3.1" value="Test" id="choice_31_3_1" type="checkbox" class="test">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3.2" value="notTest" id="choice_31_3_2" type="checkbox" class="test">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>

Using JS: Change your function to this:
$(function(){
function uncheck(e) {
var isElemChecked = e.target.checked;
// Return if the element was being unchecked
if(!isElemChecked){
return;
}
$('input').prop('checked',!isElemChecked);
$(e.target).prop('checked',isElemChecked);
}
jQuery("#choice_31_3_1").click(uncheck);
jQuery("#choice_31_3_2").click(uncheck);
})
Using CSS (no need for JS code):
Change your inputs to type=radio and update the css as
input[type="radio"] {
-webkit-appearance: checkbox; /* Chrome, Safari, Opera */
-moz-appearance: checkbox; /* Firefox */
}
<input name="input_3" value="Test" id="choice_31_3_1" type="radio">
<label for="choice_31_3_1" id="label_31_3_1">Test</label>
<input name="input_3" value="notTest" id="choice_31_3_2" type="radio">
<label for="choice_31_3_2" id="label_31_3_2">notTest</label>
Please note CSS approach would not work on IE.

https://plnkr.co/edit/o7dft84Cm4tA3GUOLt4y?p=preview
function uncheck() {
if (this.checked){ // support unchecking
$('input').prop('checked',false);
this.checked = true
}
}
You have to know which element triggered the event in order to solve it properly.
One way to solve it is the function I show above - simply mark all checkboxes to false, then mark this - the element that triggered the event - to true.

Related

how to correct check checkbox and display if is checked

i use this code to show some text (Checked) when click on 1 or more checkboxes.
I use the on because the checkboxes are dynamically created.
It seems that only IE Edge can not deal with it. I have to click twice on a checkbox to show the Checked text. In all other browsers it works immediately.
Really don't know what is wrong with the code
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons" style="display:none">Checked</div>
<script>
$(document).on('click','.rafcheckbox',function() {
var $checkboxes = $('.rafcheckbox').change(function() {
var anyChecked = $checkboxes.filter(':checked').length != 0;
$(".cb-buttons").toggle(anyChecked);
});
});
</script>
Fiddle: https://jsfiddle.net/g5tp4kjm/
Since you already have the delegate for the elements, just change it to a change event handler.
Inside that logic, toggle the hide class, but force it to have the hide class if no elements are checked.
$(document).on('change','.rafcheckbox',function() {
$('.cb-buttons').toggleClass('hide', $('.rafcheckbox:checked').length < 1);
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="rafcheckbox" value="1" />
<input type="checkbox" class="rafcheckbox" value="2" />
<input type="checkbox" class="rafcheckbox" value="3" />
<div class="cb-buttons hide">Checked</div>
Lets try it another way.
$(document).on('click','.rafcheckbox',function() {
if($('.rafcheckbox').is(':checked'))
{
//do whatever you want
}
else
{
//do the opposite
}
});

JQuery check a checkbox then un-check/disable others with the same name attribute

I have the three input checkboxes all of them have the same name attribute I want one of them is checked then others uncheck and disabled. I want to the jquery code within the function call on function and on change event like this code below or any another way work correctly.
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
var itemWithIconCheckbox = $('.topmenitems input');
var topItemTypesFunc = function() {
//Jquery code here
};
topItemTypesFunc();
topItemTypeCheckboxes.on( 'change', topItemTypesFunc);
You can do the function you want via radio buttons. Here, I have implemented a simple logic here. When a checkbox is changed ten uncheck checkbox other then the clicked one. Here is an working example.
$('input[name="menu-item-topitemtypes"]').on( 'change', function(){
if($(this).prop('checked')){
$('input[name="menu-item-topitemtypes"]').not($(this)).prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
This may help full to you
$('input[type="checkbox"]').on('change', function(){
if($(this).is(':checked')){
$(this).siblings().attr('disabled', 'true');
}else{
$(this).siblings().removeAttr('disabled', 'false');
}
})

javascript - Trigger event when any checkbox is checked/unchecked

In my HTML, I have a lot of checkboxes.
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
(Even more checkboxes ..............)
Without jQuery, how do I create an alert once any checkbox in the document is changed?
(With so many checkboxes, it will be very troublesome to add onclick="alert('Hello!');" on every single checkbox.)
This is how you would do it without jQuery:
// get all the checkboxes on the page
var checkboxes = document.querySelectorAll('input[type=checkbox]');
// add a change event listener
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(){
console.log('the checkbox changed');
});
}
Note: document.querySelectorAll is not supported in IE7 or below.
http://caniuse.com/queryselector
Clicks are bubbling through the document, you could use a single eventlistener for the parent element of these inputs. Something like this:
<form id="form">
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
</form>
JS:
document.getElementById('form').addEventListener('click', function (e) {
if (e.target.type === 'checkbox') {
alert('Checkbox');
}
});
If you don't have a form or any other common parent element (and you don't want to add a one), you can add the listener to the document as well.
A live demo at jsFiddle.
you can do like this :
HTML:
<form id="form">
<input type="checkbox" name="checkbox" /> Check me!
<input type="checkbox" name="checkbox"/> Check me as well!
<input type="checkbox" name="checkbox"/> Check me too!
<input type="checkbox" name="checkbox"/> This is a checkbox.
<input type="checkbox" name="checkbox"/> It is not a radio button.
<input type="checkbox" name="checkbox"/> Just saying.
</form>
JS:
var cbobject= document.forms[0].elements.checkbox;
for (var i=0, len=cbobject.length; i<len; i++) {
if ( cbobject[i].type === 'checkbox' ) {
cbobject[i].onclick = show_alert;
}
}
function show_alert(e){
alert("checkbox!!!")
}
DEMO:

changing the checked attribute of checkbox using jquery

I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo

Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):
<div id="ScrollCB">
<input type="checkbox" name="ALL" value="checked" checked="checked">
All (if nothing selected, this is default) <br>
<c:forEach items="${serviceList}" var="service">
<input type="checkbox" name="${service}" value="checked"> ${service} <br>
</c:forEach>
</div>
What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).
I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):
<script type="text/javascript">
$ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
$(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
Could you tell me some simple approach how to get it work? Thanks a lot!
demo
updated_demo
HTML:
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
JS:
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('div input').attr('checked', true);
} else {
$('div input').attr('checked', false);
}
});
HTML:
<form>
<label>
<input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>
JS:
$('#selectall').click(function() {
$(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});
http://jsfiddle.net/wDnAd/1/
Thanks to #Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.
FIDDLE
HTML
<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
SCRIPT
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('input:checkbox').prop('checked', true);
} else {
$('input:checkbox').prop('checked', false);
}
});
And now add this to manage the master checkbox as well...
$("input[type='checkbox'].justone").change(function(){
var a = $("input[type='checkbox'].justone");
if(a.length == a.filter(":checked").length){
$('.selectall').prop('checked', true);
}
else {
$('.selectall').prop('checked', false);
}
});
Add extra script according to your checkbox group:
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('colors[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
HTML Code:
<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>
use this i hope to help you i know that this is a late answer but if any one come here again
$("#all").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.
function FnCheckAll()
{
var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
for (i = 0; i < ChildChkBoxes.length; i++)
{
ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
}
}
function FnCheckChild()
{
if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
document.forms[0].CheckAll.checked = false;
else
document.forms[0].CheckAll.checked = true;
}
Master CheckBox:
<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />
Child CheckBox:
<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="#employee.Id" />```
You can use jQuery like so:
jQuery
$('[name="ALL"]:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
A fiddle.
var selectedIds = [];
function toggle(source) {
checkboxes = document.getElementsByName('ALL');
for ( var i in checkboxes)
checkboxes[i].checked = source.checked;
}
function addSelects() {
var ids = document.getElementsByName('ALL');
for ( var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
selectedIds.push(ids[i].value);
}
}
}
In HTML:
Master Check box <input type="checkbox" onClick="toggle(this);">
Other Check boxes <input type="checkbox" name="ALL">
You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.
$('document').ready(function(){
$('#ScrollCB input:first').bind('change', function() {
var first = $(this);
first.siblings().attr('checked', first.is(':checked'));
});
});
I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.
Here is the basic idea
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings().prop("checked",this.checked);
});
if there are other elements that are siblings, than you would beed to filter the siblings
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings(":checkbox").prop("checked",this.checked);
});
jsFiddle

Categories

Resources