Toggle between 2 check boxes using jquery or javascript - javascript

I'm having difficulty in using jquery to toggle between 2 checkboxes..Currently this is what i have.
<div id="chkBoxList" onclick="CheckBoxToggle()">
<font size="2">
<input type="checkbox" class="all" name="empType" id="empType1" value="BWR is a Full Time employee. " checked="checked" disabled="disabled"/>
Full Time
<input type="checkbox" class="all" name="empType" id="empType2" value="BWR is a Part Time employee. " /> Part Time
</font>
</div>
jquery follows thus.
function CheckBoxToggle() {
$('#chkBoxList').click(function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
$checkbox[1].checked;
$checkbox.trigger('change');
});
}
But this either toggles both to checked or unchecked. Since, initial value for one is checked and disabled, when clicked on second i want other to be checked and disabled while the first will be unchecked and disabled. Any help is appreciated.

<html>
<body>
<form name=f1 id=f1>
<input type=checkbox name=chk1 id=chk1 onclick=javascript:document.f1.chk2.checked=!document.f1.chk1.checked;> Check 1<BR>
<input type=checkbox name=chk2 id=chk2 onclick=javascript:document.f1.chk1.checked=!document.f1.chk2.checked;> Check 2<BR>
</form>
</body>
</html>

You need to use .each() to loop through $checkbox.
$(function(){
$('#chkBoxList').click(function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.each(function(){
$(this).prop('checked', !$checkbox[0].checked);
});
});
});
http://jsfiddle.net/mPstq/1/

$('input.all').click(function(e){
$('input.all').prop('checked', false).prop('disabled',false) ;
$(this).prop('checked', true).prop('disabled', true) ;
}) ;

Related

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');
}
})

Check box not toggling

The toggle check box function is only working once and after the first instance it doesnt work. Any help?
Here is the jsfiddle:
http://jsfiddle.net/66gmK/
<script>
$(document).ready(function() {
$(document).on('click','#1',function(){
$("INPUT[type='checkbox']").each(function(){
var Checked = $(this).attr('checked');
$(this).attr('checked', !Checked);
});
});
});
</script>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<input name="checkbox" type="checkbox" id="1" value="0" />
<label for="1" >Toggle All</label>
</p>
<p>
<input name="checkbox" type="checkbox" id="2" value="0" />
ahmed</p>
<p>
<input name="3" type="checkbox" id="3" value="0" />
<label for="3">omar</label>
</p>
</form>
</body>
Move the Checked variable out of the each because the this context changes in the each, it refers to the checkbox in the loop, not the toggle checkbox. Remove the ! not operator when changing the checked property. Also use prop instead of attr for the checked property.
Demo
$(document).ready(function() {
$(document).on('click','#1',function(){
var Checked = $(this).prop('checked');
$("INPUT[type='checkbox']").each(function(){
$(this).prop('checked', Checked);
});
});
});
your jquery
on each function , you should not change the property of toggle checkbox.
$(document).ready(function() {
$(document).on('click','#1',function(){
$("INPUT[type='checkbox']").not(this).each(function(){
var Checked = $(this).prop('checked');
$(this).prop('checked', !Checked);
});
});
});
Demo
You can also use
$(document).ready(function() {
$('#1').on('click',function(){
var Checked = $(this).prop('checked');
$.each($("input[type='checkbox']"), function(i,e){
$(e).prop('checked', Checked);
});
});
});

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

When i check the checkbox for the first time the program executes.But after unchecking,NOT

Here is my script.
When I check the checkbox for the first time the program executes. But after unchecking (it will hide the output), when I want to check it again it will not show my results.
<script>
$(document).ready(function() {
$('#chk input').change(function(){
if($(this).is(":checked")) {
// checkbox is checked -> do something
var url=$(this).attr('value');
$('#headlines').load('Subcri.php?searchquery='+ url);
return false;
} else {
// checkbox is not checked -> do something different
$('#headlines').hide();
}
});
}); // end ready
Here is my html part
<html>
<form id="chk" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="searchquery" class="click" id="" value="bird" >Checkbox
<br />
<input type="checkbox" name="searchquery" class="click" id="" value="pet" >Checkbox
<br />
<input type="checkbox" name="searchquery" class="click" id="" value="school" >Checkbox
<br />
<input type="checkbox" name="searchquery" class="click" id="" value="Disney" >Checkbox
<br />
</form>
<div id="headlines"></div>
</html>
You did not show headline div after hiding it. you need to show it if it is hidden.
replace your js script by this:
<script>
$(document).ready(function() {
$('#chk input').change(function(){
if($(this).is(":checked")) {
// checkbox is checked -> do something
var url=$(this).attr('value');
if(! $('#headlines').is(":visible")){
$('#headlines').show();
}
$('#headlines').load('Subcri.php?searchquery='+ url);
return false;
} else {
// checkbox is not checked -> do something different
$('#headlines').hide();
}
});
}); // end ready
live demo : http://jsfiddle.net/qsDn5/15/
Use This
if(! $('#headlines').is(":visible")){
$('#headlines').show();
}
It wil Show

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources