Exclusive input checkboxes - enable to uncheck by clicking on current checked input - javascript

I did an exclusive menu of 2 input checkboxes : each input checkbox corresponds to a different case : (Player Vs Computer) and (Player1 Vs Player2) and each case is associated to 2 buttons (which work as I want).
My issue is that I would like to add a functionality, i.e enable to uncheck the current checked box by clicking on the current checkbox (this one which is already checked).
For the moment, I have to click directly on the other input checkbox to uncheck the current one; I would like to get the both functionalities.
Here's the current code which handles these 2 exclusive input checkbox :
// Check input checked
checkBoxState = $('#'+gameType+'').find('.game').prop('checked');
// Set oneButtonClicked to no for restore
$('#formGame').prop('oneButtonClicked', 'no');
// Handling input.game
$('#'+gameType+'').find('.game').prop('checked', !checkBoxState);
//$('#'+gameType+'').siblings().find('.game').prop('checked', checkBoxState);
// Set pointer-events to all for formGame
$('#formGame').css('pointer-events', 'all');
// Handling button.btn
$('#'+gameType+'').find('.btn').css('pointer-events', 'none');
$('#'+gameType+'').siblings().find('.btn').css('pointer-events', 'all');
$('#'+gameType+'').find('.btn').prop('disabled', checkBoxState);
$('#'+gameType+'').siblings().find('.btn').prop('disabled', !checkBoxState);
gameType is the current type of game (Player Vs Computer or Player1 Vs Player2).
input.game represent the input checkboxes
button.btnrepresent the 2 buttons available for each ìnput.game.
How can I add this functionality, i.e uncheck by clicking on current checked, or uncheck by clicking directly on the other checkbox?
Update 1
A click on a checkbox should automatically set its negation to the other checkbox.
Update 2
I tried to adapt the solution given by #CodeAt30 by doing simply:
gameType = (gameType == 'PlayerVsComputer') ? 'Player1VsPlayer2' : 'PlayerVsComputer';
$('#'+gameType).find('.game').prop('checked', !$('#'+gameType).find('.game').prop('checked'));
This solution works for uncheck the current checkbox and check its siblings().
But now, I can't select directly the other checkbox unlike to the JS Fiddle: Uncheck checkbox by clicking directly on the other no-checked "input checkbow"

https://jsfiddle.net/m059rr88/
HTML
<input id="one" type="checkbox"></input>
<input id="two" type="checkbox"></input>
Javascript:
let afterFirstClick = false;
$("input").click(function(){
let passiveCheckboxId = "one";
if($(this).attr("id") === "one"){
passiveCheckboxId = "two"
}
if(afterFirstClick){
$("input#" + passiveCheckboxId).prop("checked", !$("input#" + passiveCheckboxId).prop("checked"));
}
afterFirstClick = true;
});

Easier than you might think:
$('input.game').click(function(){
$('input.game').not(this).removeAttr('checked');
});
What is does is assign a click handler to the checkboxes that removes the checked attribute from all other boxes. The status of the current box is handled by the native checkbox code, so checking and unchecking will work normally.
... or ...
$('input.game').click(function(){
if (this.checked) {
$('input.game').not(this).removeAttr('checked');
} else {
$('input.game').not(this).trigger('click');
}
});
This code will allow you to swap checkboxes by clicking on either one. Once a box is checked there is no way to uncheck it, like a radio button.

Related

How to uncheck all checkboxes except the one using jQuery?

I have a form that has multiple checkbox groups.
Each checkbox option has a custom html 5 attribute called itemtype. When the input of type="checkbox" changes, I need to evaluate the checkbox that was just selected. If the value of it's data-itemtype is equal to 'Skipper', I want to uncheck all other checkboxes that belong to the same group.
In other words, assume that I have multiple checkboxes and one of the checkbox options has a label called "None", if the user checks "None", Nothing should be selected but "None". I can't use a radio button here as I want the user to be able to check multiple options if "None" is not selected.
Here is a break down of my code
CHECKBOX GROUP 1
<input name="control_307[0][307:1003]" id="item_307_1003_0" value="307:1003" data-itemtype="Answer" type="checkbox"> Zulauf Ltd<br>
<input name="control_307[0][307:361]" id="item_307_361_0" value="307:361" data-itemtype="Answer" type="checkbox"> Ziemann, McLaughlin and Kohler
<input name="control_307[0][308:1013]" id="item_307_1013_0" value="308:1013" data-itemtype="Skipper" type="checkbox"> None<br>
CHECKBOX GROUP 2
<input name="control_1000[0][1000:999]" id="item_1000_999_0" value="307:1003" data-itemtype="Answer" type="checkbox"> First Options<br>
<input name="control_1000[0][1000:666]" id="item_1000_666_0" value="1000:666" data-itemtype="Answer" type="checkbox"> Some other option
<input name="control_1000[0][1000"123]" id="item_1000_123_0" value="308:1013" data-itemtype="Skipper" type="checkbox"> None<br>
I have create a fiddle to show you what I have done along with the entire form https://jsfiddle.net/8yf0v3xt/13/
I tried to do something like this but is is not working
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
$(this).attr('checked', false); //uncheck all the boxes for the current group
skipper.attr('checked', true); //re-check the box that caused everything to uncheck
}
}).change();
What can I do to unckecl all the option if "None" is selected?
Hope this would work for you
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
}
}).change();
UPDATE
WORKING FIDDLE
UPDATE 2
WORKING FIDDLE 2
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
//$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
//THIS IS IMPORTANT
$(this).closest(".survey-control-fieldset").find(":checkbox").not(skipper).prop("checked",false);
}
}).change();
UPDATE 3
WORKING FIDDLE 3
$(:checkbox).change(function(){
var skipper = $("input:checkbox[data-itemtype='Skipper']");
if( skipper.is(":checked")){
//$(":checkbox").attr('checked', false); //uncheck all the boxes for the current group
//skipper.attr('checked', true); //re-check the box that caused everything to uncheck
//$(":checkbox").not(skipper).prop("checked",false);//THIS IS IMPORTANT
//THIS IS IMPORTANT
$(this).closest(".survey-control-fieldset").find(":checkbox").not(skipper).prop("checked",false);
}
else
{
$(this).closest(".survey-control-fieldset").find(":checkbox[data-itemtype='Skipper']").prop("checked",false);
}
}).change();
CONCLUSION
Few points I noticed wrong in your code are as follows.
You were using $(this).attr("checked",false); to uncheck all
checkboxes which is wrong. $(this) points to CURRENT SINGLE
ELEMENT only, not all.
You were using .attr("checked",false) which is also incorrect, it
should be either .attr("checked","checked") or
.prop("checked",true).

How do I keep a Checkbox disabled in Internet Explorer

I have an application that pairs a textbox with a checkbox. The user can check the checkbox, which auto-populates the textbox with a specific dollar amount. If they uncheck the checkbox, this sets the textbox's value to zero. They can also enter a dollar amount in the textbox and an onblur event handler toggles the checkbox.
The problem comes when they enter a dollar amount in the textbox and then check the checkbox with a mouse click. This fires the onblur event, which automatically toggles the checkbox, then recognizes the mouse click, setting the dollar amount back to zero.
My solution was to disable the checkbox on textbox focus, then enable the checkbox on textbox onblur event.
This works well in Firefox and Chrome, but fails miserably in Internet Explorer. FF and Chrome ignore any mouse click on the checkbox when it is disabled. This means that the onblur event does not fire, when the user clicks on the disabled checkbox after entering a dollar amount in the textbox. The checkbox stays disabled. They have to click elsewhere on the page for it to be enabled.
In Internet Explorer, the onblur event fires when the user clicks on the disabled checkbox, and the checkbox recognizes the click, right after it is checked with the onblur event handler, unchecking the checkbox, setting the textbox value back to zero.
I need a better solution. How do I get Internet Explorer to act like FF and Chrome, ignoring any click on a disabled checkbox. Or, is there a more elegant solution altogether?
Example Code:
<input type=textbox id=textbox1 onFocus=CheckboxDisable('pairedWithTextBox1'); onBlur=CheckboxEnable('pairedWithTextBox1');>
<input type=checkbox id=pairedWithTextBox1>
Javascript code:
function CheckboxDisable(id){
document.getElementById(id).disabled = true;
}
function CheckboxEnable(id){
document.getElementById(id).disabled = false;
}
Short of a real solution. .. you COULD set a data attribute on the check box on focus of the text element, then check for it on the cb on click event and override the default action. ..
Aside from a possibly confusing user interface design (can't say for sure since you genericized the problem too much), the problem is that the checkbox and textbox are both views of the same model.
The model is the dollar amount.
The textbox is a view of the
actual dollar amount.
The checkbox is a view that indicates
whether the amount is 0 or something else.
Your current design is complex, which is not by itself a bad thing, because the event handlers for the text box onblur and checkbox onclick are also controllers of the model. (This is a bit of an oversimplification; the controller also consists of the browser and all the JavaScript code.)
Here is a solution that helps illustrate this fact. It works based on the business rule that once the user has modified the value in the textbox (to a non-zero value) changing the state of the checkbox from unchecked to checked will not update the model (or the textbox view).
var txtAmount = document.getElementById('txtAmount');
var chkAmount = document.getElementById('chkAmount');
var defaultValue = 0;
var model = defaultValue;
function UpdateViews() {
if (model === 0) {
chkAmount.checked = false;
}
txtAmount.value = model.toFixed(2);
}
function UpdateModel(val) {
// update model when view changes
model = parseFloat(val) || defaultValue;
UpdateViews();
}
UpdateViews(); // set initial view
txtAmount.onchange = function () {
UpdateModel(this.value);
};
chkAmount.onclick = function () {
if (this.checked) {
// when user checks the box, only update model if not yet modified
if (model === defaultValue) UpdateModel(55); // hardcoded default of $55
} else {
UpdateModel(defaultValue);
}
};
<input type='text' id='txtAmount' />
<input type='checkbox' id='chkAmount' />
If I were in your case, I will put an If-Else in the click event of the checkbox...
Something like:
if (!String.IsNullOrEmpty(textBox1.Text) | textBox1.Text != "0")
{
// Do nothing since textbox1 already has a value greater than zero
}
else
{
// Enter amount in textbox
}
Try this..
function CheckboxDisable(id){
$("#id").attr("disabled", "disabled");
}
function CheckboxEnable(id){
$("#id").removeAttr("disabled");
}

How to do an action when unchecking a checkbox?

Well basically I have 3 check boxes. Each of them has a boolean which gets turned to true when a button is clicked and the box is checked.
However is it possible to do an action, when unchecking a check box without having to hit another button to trigger an event first.
so as example:
I select check box 1 & 2. =>
I hit start button -> boolean for check box 1 & 2 gets set to true. =>
I uncheck check box 2 -> trigger event
Use the onchange attribute of the input tag which activates some javascript; eg:
HTML:
<input type = "checkbox" id = "checkbox_id" onchange = "change()" value = "foo">
JavaScript:
function change()
{
//do something
}

Jquery click event with binded event

Hi guys I am having a problem with Events. I have a checkbox list and I have a main check box that checks all boxes. When I clickEvent some of my checkbox list items it should add data-id attr to the "selected obj". So in my case when I press main check box to check all others every thing is ok (it simply clicks all other elements). but when i do that it empties my array. I mean if i uncheck it will be the way it supposed to be but checked (when uncheck it fills when i check it empties).
......
var selected = {};
var reload = function(){
selected = {};
$('.checkbox_all').unbind('click');
$('.table_checkbox').unbind('click');
$('.checkbox_all').bind('click', checkAll);
$('.table_checkbox').bind('click', checkMe);
}
var checkMe = function(e){
var checkbox = $(e.target);
var id = checkbox.attr('data-id');
//console.log(id);
if(checkbox.attr('checked')){
selected[id] = id;
}else{
if(selected[id]) delete selected[id];
}
console.log(selected);
}
var checkAll = function(e){
if($(e.target).attr('checked')){
$('.table_checkbox').each(function(){
if($(this).attr('checked') === false){
$(this).click();
}
});
}else{
$('.table_checkbox').each(function(){
if($(this).attr('checked') === true){
$(this).click();
}
});
}
//console.log(selected);
}
.......
HTML:
<tr><th class="table-header-check"><input type="checkbox" class="checkbox_all"/></th></tr>
<tr class=""><td><input type="checkbox" data-id="5" class="table_checkbox"></td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="6" class="table_checkbox"</td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="8"
....ETC\
My problem is that when i click .checkbox_all it should click on all .table_checkbox(that r cheched or uncheched)... it just clicks all checkboxes like a main checkbox... it works fine, but i have an event all other checkboxes if i click em i add some data to array when i unclick em it removes data from array.... so when im clicking checkboxes sepperatly they add /remove data to array properly... but when im clicking on main checkbox... it clicks on right checkboxes but the data array is empty when all checked and full when all unchecked... it must be the opposite way
Could you instead go for a cleaner solution, and generate selected on the fly? See here for an example (and a JSFiddle for everyone else): http://jsfiddle.net/turiyag/3AZ9C/
function selected() {
var ret = {};
$.each($(".table_checkbox"),function(index,checkbox) {
if($(checkbox).prop("checked")) {
ret[$(checkbox).prop("id")] = true;
}
});
return ret;
}
** EDIT: **
If you're looking to have an array that is added to and removed from, then this JSFiddle (http://jsfiddle.net/turiyag/pubGb/) will do the trick. Note that I use prop() instead of attr(), in most cases, especially this one, you should use prop() to get the value you want.
To work with your own code you need to understand the order of events. When you programmatically call click() on the checkbox the javascript (checkMe() for children) executes before the state of each child checkbox is changed (e.g., adding attribute 'checked'). It is because of this reason that the checkMe() function was adding and removing ids in the selected array in the reverse order. You can confirm this by adding the following debug line in the checkMe function:
console.log('Checked state of checkbox id:' + id + ' is: ' + checkbox.prop('checked'));
Case1: Clicking checkAll when it is Unchecked; it calls checkMe() for each child checkbox but finds the 'checked' attribute as undefined. So it executes the delete code. After executing checkMe the 'checked' attribute is added on the checkbox.
Case2: Clicking checkAll when it is Checked; the checkMe() function finds the 'checked' attribute previously added and fills the array. Later an event is probably fired to remove the 'checked' attribute.
I changed the following lines to quickly test this and seems to be working:
Bind checkMe on change event instead of click in reload function:
$('.table_checkbox').bind('change', checkMe);
Change the condition for unchecked children in checkAll function when the .checkbox_all is checked:
if($(this).prop('checked') === false) {/*call child click*/}
//Use prop instead of attr because it takes care of 'undefined' cases as well. If you want to keep using attr because you're on an older version of jquery then add something like:
typeof $(this).attr('checked') == 'undefined'
and also the condition when .checkbox_all is unchecked:
if($(this).prop('checked') === true) {/*call child click*/}
Hope this helps. Here's a jsbin to play with..

Need help with javascript regarding radiobuttons

I want to disable the radiobutton the second time it is clicked..I want to put some code in the head..that when a radiobutton is clicked the second time,, it isnt marked anymore..
I want to check and uncheck the radiobutton with each click.
Note: I generate 20 radiobuttons dynamically
Take into account that it is a Radiobutton that is run on the server:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton.aspx
UPDATE: This is the only event that the RadioButton (asp WebControl run at="server") has:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
if (rad.Checked)
{
rad.Checked = false;
}
}
I can uncheck it after each post back..but unless a post back doesnt happen, i cant select and deselect it.. Thats the problem!! :(
I think you should keep with the standard use of RadioButtons, by saying this - use CheckBoxes instead, and clear all checkboxes if a different one is clicked...so when a checkbox is clicked the second time the standard uncheck will occur.
if i get you right then
all u need is a flag attribute of how many times u have clicked on the radio button and each time u click the radio the attribute increased by 1 and check the attribute every click if its 2nd time then disable the radiobutton
so you need to generate ur radiobuttons like this
<input type='radio' onclick='radioClick(this);' how_many_clicked='0' id='whatever id u need' name='whatever name u need' />
and create ur function in the head like the following
function radioClick(e) {
var flag = e.getAttribute('how_many_clicked');
var times = Number(flag);
times += 1;
e.setAttribute('how_many_clicked', times.toString())
if (times > 1) {
e.checked = false;
e.setAttribute('how_many_clicked', "0");
}
else {
e.checked = true;
}
}
Id create an empty array. For every radiobutton you create, add its ID to the array as the key and set its value to 0. This will be the count for the specific button. Whenever a radiobutton is clicked, check the buttons ID against the array, if its less than 2, increment it. If not, disable the current button.
EDIT : didn't realize you were checking if it was already checked, thoguht it was the number of times checked.
$("#id").is(":checked")
Should suffice
Another note ...if all you're doing is disabling an element from being accessed by the user, you should handle this event on the client side. You'll be using unnecessary server callback for functionality easily achievable via javascript. Use jquery click event handlers which can be generic enough for you not to have to use identifiers, making the job that much easier.
Cheers

Categories