Clearing/Un-selecting Radio button on second click - javascript

I have a LOT of radio buttons on a form I'm creating.
The reason why I am using radio buttons and not check box's is because I only want to let a user select one or none.
The bad thing about a radio button though is, once selected, it can't be undone. I am trying to add the feature of clearing a group of radio box's when it's clicked for the second time.
My method that I am implementing now works if I have a group of radio buttons I want to target individually but not if I want to implement it for ALL radio button groups on the page.
When I use multiple radio button groups, it will randomly un-select a radio button when I try to select a different option.
If anyone could help me out, it would be greatly appreciated.
JSFIDDLE for only one group of radio buttons (works)
If you change to this code instead and target an individual name, it works.
$('input[name="rad"]').click(function()
JSFIDDLE for multiple groups of radio buttons (doesn't work)
I am trying to be able to target all my radio button groups at once, because there are a LOT.
$(function(){
$('input[type="radio"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});

So you just need a way to check/uncheck reliably by name groups.
Something like this should work:
$('input[type="radio"]').on('click change', function () {//on click/change
$(this).prop('checked')//if checked
? $(this).prop('checked',false).data('waschecked', false)//uncheck
: $(this).prop('checked',true).data('waschecked', true)//else check
.siblings('input[name="'+$(this).prop('name')+'"]').data('waschecked', false);//make siblings false
});
kept the .data('waschecked', ...) in case you needed to have that value, but it works without it like this:
$('input[type="radio"]').on('click change', function () {//on click/change
$(this).prop('checked')//if checked
? $(this).prop('checked',false)//uncheck
: $(this).prop('checked',true);//else check
});
made a fiddle: http://jsfiddle.net/filever10/ZUb65/

Try changing the line to use the name attribute of the clicked radio in the selector expression
$radio.siblings('input[name='+ $(this).attr('name') +']').data('waschecked', false);
You just need to clear your "waschecked" flag on the other radios of the same group.
http://jsfiddle.net/jammykam/BtLxY/15/
And just in case you do need to target using onchange: http://jsfiddle.net/jammykam/BtLxY/27/
$('input[type="radio"]').on('change', function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name='+ $(this).attr('name') +']').data('waschecked', false);
});

If you are using a simple primary to secondary relationship then try this out:
$('input[type="radio"][name="main_radios"]').on('change', function(){
$('input[type="radio"][name="secondary_radios"]').prop('checked', false);
$('input[type="radio"][name="third_radios"]').prop('checked', false);
$('input[type="radio"][name="fourth_radios"]').prop('checked', false);
// combine it all into one call if you really feel like it
$('input[type="radio"][name="secondary_radios"], input[type="radio"][name="third_radios"], input[type="radio"][name="fourth_radios"]').prop('checked', false);
});
Uncheck all radios that are not "this" name
// Listen for ANY radio to be changed
$('input[type="radio"]').on('change', function(){
// remember name of selected radio
var checked_name = $(this).attr('name');
// target only radios that are not "this" name and uncheck them
$('input[type="radio"]').filter(function(){
if($(this).attr('name') != checked_name){
return true;
}
else{
return false;
}
}).prop('checked', false);
});

Related

Checkbox to control radio buttons

I have a checkbox and 3 radio buttons, I'm trying to have one of the radio buttons selected if the checkbox is checked and have any of them un-selected if the checkbox is unchecked.
My solution works on the first run, but wont select the radio button after the first click.
$('#checkbox-h-2g').click(function () {
if ($('#checkbox-h-2g').is(":checked")) {
$('#r1').attr('checked', true);
}if (!$('#checkbox-h-2g').is(":checked")) {
$('#r1 , #r2, #r3').attr('checked', false);
}
});
Use .prop() instead of .attr() to set properties, Also your code can be improved as
$('#checkbox-h-2g').change(function () {
if (this.checked) {
$('#r1').prop('checked', true);
}else{
$('#r1 , #r2, #r3').prop('checked', false);
}
});

Uncheck a Checkbox using Jquery

I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.
The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.
This is what I have so far, the first if else works but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Example fiddle
Note I restricted the fiddle to 2 selections so that it's easier to test.
You need this $(this).prop('checked', false);
You should be saying
$(this).attr('checked', false)
instead of
this.attr('checked', false)
You need this $(this).prop('checked', false);
Also this is a javascript object, if you want to use jquery you should prefer $(this).

Fixing toggle all behavior in checkbox element

I'm trying to toggle all checkboxes on a table and my code works but has a few issues and I don't find how to get ride of them. So here is the code:
$(function () {
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").click();
});
});
Take a look at this Fiddle I setup for testing and do this tests:
Mark the first checkbox (the one at table heading level) the rest of them inside #codigoArancelarioBody get checked and this is right
Mark first the checkbox at the first row (the only at table body level) and then mark the toggleAll you will see how things goes wrong since if I check the toggleAll them all should remain checked and that's the wrong part on my code
How I can fix this? Also I'll like to add a class 'removedAlert' to those TR I mark, how?
You need two click event handlers, one for the check/uncheck all box and one for the other ones
JS
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").prop("checked", $toggle);
});
$("#codigoArancelarioBody input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$('#toggleCheckbox').prop("checked", false);
} else if ($("#codigoArancelarioBody input:checkbox").length == $("#codigoArancelarioBody input:checkbox:checked").length) {
$('#toggleCheckbox').prop("checked", true);
}
});
DEMO
since the same code will be applied in a lot of places on my code and
to avoid DRY, I'll like to pass the selector as a parameter in all
your code solution could you edit your post to achieve this?
$toggleCheckBox = $('#toggleCheckbox');
$checkBoxTbody = $("#codigoArancelarioBody");
$toggleCheckBox.on('click', function () {
var $toggle = $(this).is(':checked');
$checkBoxTbody.find("input:checkbox").prop("checked", $toggle);
});
$checkBoxTbody.find("input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$toggleCheckBox.prop("checked", false);
} else if ($checkBoxTbody.find("input:checkbox").length == $checkBoxTbody.find("input:checkbox:checked").length) {
$toggleCheckBox.prop("checked", true);
}
});
DEMO
If you don't need the "click" event for something else you can do this:
$(function () {
$('#toggleCheckbox').on('change', function () {
var toggle = $(this).is(':checked');
$("#codigoArancelarioBody").find("input:checkbox").prop('checked', toggle ).closest('tr').addClass('removedAlert');
});
});
The code is actually executing what you told it to do, i.e. every time I click the checkbox on top click to other checkboxes. This way if a box is checked it will uncheck itself, because it won't mind if the top is checked or not.
What you really want is "when I check the box on top, check all the others, when I uncheck it, then uncheck all the others", which is sort of different as you see.
Try this:
$(function () {
// best practice: always store the selectors you access multiple times
var checkboxes = $("#codigoArancelarioBody").find("input:checkbox"),
toggleAll = $('#toggleCheckbox');
toggleAll.on('click', function () {
// is the top checkbox checked? return true, is it unchecked? Then return false.
var $toggle = $(this).is(':checked');
// .prop('checked', true) makes it checked, .prop('checked', false) makes it unchecked
checkboxes.prop('checked', $toggle);
});
});
see: http://jsfiddle.net/gleezer/nnfg80x1/3/

select only one checkbox and add class for the checked input

I have a list of checkbox and want to select the only one check box and add the class for the checkbox input and select another checkbox remove that class from the existing checkbox
$('input.myclass').click(function ()
{
var id = $(this).attr('id').replace('image-','');
$('input.myclass:checked').not(this).removeAttr('checked');
var sFilter = "";
$('input.myclass[type=checkbox]').each(function () {
sFilter = sFilter + (this.checked ? $(this).val() : "");
});
check();
});
function check(){
var a = $('input:checkbox[name=cover_image]:checked').val();
alert(a);
}
I want to select only one checkbox and class for the checked checkbox if that checkbox not checked then remove the class for that
If you really want to use checkboxes(and not radio buttons) for some reason, do something like this:
$('input:checkbox').on('click', function () {
$('input.selected').removeClass('selected').prop('checked', false);
$('input:checked').addClass('selected');
});
Edit: Removing the attribute works, but property manipulation is a slighty better way of doing it(as suggested by RobG)
For your purpose first remove classes from all checkbox and unchecked them and then add class to clicked checkbox and checked it as below
$("input[type='checkbox']").on('click', function () {
$("input[type='checkbox']").removeClass('selected').attr('checked', false);
$(this).addClass('selected').attr('checked', true);
});
Check this Fiddle for your question
you may use on() to listen the changes on group of checkboxes.
var $checkBoxes = $(":checkbox").on("change", function () { // Here listening the changes on checkbox using on()
$checkBoxes.removeClass("change").attr("checked", false); // remove the class from existing Checkbox
$(this).addClass("change").attr("checked", true); // adding the class for the currenly checked checkbox
});
working FIDDLE is here

Check/Uncheck all checkboxes

I've seen many check/uncheck all checkboxes scripts. But far most does not respect that if I toggled all checkboxes using the "checked all"-checkbox and then uncheck a single one in the list, the "checked all" checkbox is still checked.
Is there an elegant way of handling this case?
$('#checkAll').click(function() {
if(this.checked) {
$('input:checkbox').attr('checked', true);
}
else {
$('input:checkbox').removeAttr('checked');
}
});
$('input:checkbox:not(#checkAll)').click(function() {
if(!this.checked) {
$('#checkAll').removeAttr('checked');
}
else {
var numChecked = $('input:checkbox:checked:not(#checkAll)').length;
var numTotal = $('input:checkbox:not(#checkAll)').length;
if(numTotal == numChecked) {
$('#checkAll').attr('checked', true);
}
}
});
Demo: http://jsfiddle.net/ThiefMaster/HuM4Q/
As pointed out in the question's comment, a regular checkbox is not perfect for this. My implementation disables the "check all" box as soon as one checkbox is unchecked. So, to uncheck all still-checked checkboxes you'll have to click twice (first to re-check the unchecked ones and then to uncheck all other ones).
However, with a tri-state checkbox this might still be necessary as the state order might be unchecked->indefinite->checked->unchecked, so you'd need two clicks to come from indefinite to unchecked.
Since you probably don't want to check ALL checkboxes on your page with "Check All", replace input:checkbox with e.g. .autoCheckBox or input.autoCheckBox:checkbox and give those checkboxes class="autoCheckBox".
If you want all checkboxes inside a certain form, simple use #idOfYourForm input:checkbox or form[name=nameOfYourForm] input:checkbox
You can achieve this by attaching a click handler to each of the target checkboxes, and have that handler un-check the "control" checkbox based on the collective state of those target checkboxes. So, something like this:
// Control checks/unchecks targets
$('#controlcheckbox').click( function(){
$('.targetcheckboxes').attr('checked', this.checked );
});
// Targets affect control
$('.targetcheckboxes').click( function(){
if( $('.targetcheckboxes:not(:checked)').length ){
$('#controlcheckbox').attr('checked',false);
}
});
Even better -- you could attach this logic to an enclosing container element, and watch for the event using .delegate():
$('#some_container').delegate('.targetcheckboxes','click',function(){...} );
$("#selectall").click(function(){
var checked = $("#selectall").attr("checked");
$(".selectone").attr("checked",checked);
});
For setting select all
$(".selectone").click(function(){
var net = $(".selectone").map(function(){ return jQuery(this).attr("checked");}).get();
var flg = true;
if(jQuery.inArray(false, net)){
flg= false;
}
$("#selectall").attr("checked",flg);
});
Perhaps something like this:
$('tbody input:checkbox').change(function(){
if ($(this).closest('tbody').find('input:checkbox').not(':checked').length) {
$('#checkAll')[0].checked = false;
}
});
This assumes that #checkAll is in the thead section of your table.

Categories