Jquery check if radio button is checked - javascript

I am trying to uncheck a radio button if it is checked, and likewise check a radio button if it is unchecked. However, it is always saying it is checked when it isn't.
Here is my code:
$('input[type=radio]').on('click', function() {
if ($(this).attr('checked') == 'checked') {
$(this).attr('checked', false);
} else {
$(this).attr('checked', true);
}
});
The above code always hits the first part of the if. I've also tried
$(this).is(':checked')
and
$(this).val()
and
$(this).attr('checked') == true
but nothing seems to be working.
How can I get this to work?

Here is the fiddle hope this myt help:
<input type="radio" name="" value="1000" align="middle" id="private_contest">1000 is the value<br>
<input type="radio" name="" value="2000" align="middle" id="private_contest">2000 is the value
and relevant jquery is:
$('input[type=radio]').on('click', function () {
$(this).siblings().prop('checked', true);
$(this).prop('checked', false);
});

You need to remove the attribute checked to uncheck, and add the attribute to check the radio button. Do not assign value to it:
<input type="radio" name="radio1">
<input type="radio" name="radio1" checked>
use:
$(this).addAttr("checked")
$(this).removeAttr("checked")

This should never fail, but it's a different approach.
Target the parent, and return which radio IS checked, rather than looking at all of them.
Just an idea
var myRadio;
$('#radioParent input:radio').click(function() {
myRadio = $(this).attr('id');
//console.log(myRadio);
//return myRadio;
});

I am not sure why this received negative votes. The usage of a radio button is so that you can have 0 or 1 options to select from, and a checkbox list is if you need 0 or many options selected. But what if you want to undo a radio button selection for an optional question?
I solved this by creating another attribute on radio buttons called "data-checked".
Below was the implementation:
$('input[type=radio]').on('click', function() {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('data-checked') == 'true';
// set 'checked' to the opposite of what it is
setCheckedProperty(radioButton, !radioButtonIsChecked);
// you will have to define your own getSiblingsAnswers function
// as they relate to your application
// but it will be something similar to radioButton.siblings()
var siblingAnswers = getSiblingAnswers(radioButton);
uncheckSiblingAnswers(siblingAnswers);
});
function uncheckSiblingAnswers(siblingAnswers) {
siblingAnswers.each(function() {
setCheckedProperty($(this), false);
});
}
function setCheckedProperty(radioButton, checked) {
radioButton.prop('checked', checked);
radioButton.attr('data-checked', checked);
}
On the page load, set the data-checked property to true or false, depending on whether or not it is already checked.
$(document).ready(function() {
$('input[type=radio]').each(function () {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('checked') == 'checked';
setCheckedProperty(radioButton, radioButtonIsChecked);
});
});

Related

condition on radio button onclick, if false don't check

onclick of one radio button i have to check one condition if true i have to check it or restore to same old status,
html
<input type="radio" name="test" id="radio0" onclick="myFunction()" checked />
<input type="radio" name="test" id="radio1" onclick="myFunction()" />
<input type="radio" name="test" id="radio2" onclick="myFunction()" />
JS
globalCondition = false;
function myFunction()
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
As I said in comment return in the function will not do anything as you're not returning the function value in the in-line code.
Although the other solutions offered are correct, to keep your code unobtrusive, you should not have inline JS at all (remove the onclick='s).
I realize the question was not tagged jQuery, but maybe it should have been: Instead on onclick you should use a jQuery event handler, selecting only the set of radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/KVwL3/1/
globalCondition = false;
$(function(){
$("[name=test]").click(function(e){
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false;
// or
e.preventDefault();
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
});
});
Notes:
DOM ready event:
$(function(){ YOUR CODE HERE }); is a shortcut for $(document).ready(function(){ YOUR CODE HERE});
Selectors
If an attribute [] selector = value contains special characters it needs to be quoted:
e.g.
$('[name="IstDynamicModel[SD_WO_CREATE]"]')
There are any number of selectors that will choose just the three radio buttons. As this is a simple one-off connection, at startup, there is no real speed difference between any options, but you would normally try and make the selector specific in ways that might make use of various lookup tables available to the browser:
e.g.
$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')
This will be slightly faster as it will reduce the slowest check (the name=) to only radio inputs.
try this:
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
e.preventDefault();
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
USe like this
<input type="radio" name="test" id="radio1" onclick="return myFunction()" />
javascript
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
return true;
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}

jquery not registering one of my radio buttons as selected

I have a radio button selection that jquery is able to loop through them and read the values for each one just fine, but jquery can only detect when one of them has been selected. When selecting the other one, jquery just ignores it and tells me none have been selected.
jquery:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = false;
}
});
html:
<input type="radio" id="upload" name="banner_type" value="upload" />
<input type="radio" id="html" name="banner_type" value="html" />
"upload" is being ignored by jquery, "html" is not
Im doing it this way:
valid=false;
$('[name="banner_type"]').each(function() {
if($(this).is(':checked'))
valid = $(this).val();
});
So each time You check for radio being checked, valid value is renewed.
here's fiddle for You. Function "check" checks validity, returning false if none is selected.
http://jsfiddle.net/CLaDG/
The else part is setting value for valid but not returning it. Also the value is always false for second radio button. Try this:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = $(this).val();
return valid;
}
});
This can be written shorter and better but right now I am just fixing the issue I see.
not sure which version of jQuery you are on, but try using jQuery.prop as well as delegated event on the container might be cleaner, such as:
$('.your-radios-container').on('change','[name="banner_type"]',function(){
valid = $(this).prop('checked');
});
I have forked your fiddle to show you how it could work:
http://jsfiddle.net/AcMBR/2/

Multieple CheckBoxes dynamically check uncheck based on selected checkbox + MVC3 + jQuery/Javascript

I have a HTML form with checkboxes as below,
when I select ALL, other check boxes {HR, FINANCE, IT, SALES} should get checked
When I un select ALL, other checkboxes {HR, FINANCE, IT, SALES} should get unchecked
When everything is checked and of one the checkboxes {HR, FINANCE, IT, SALES} is unchecked, ALL should be unchecked
Below is the markup of my HTML.... how can I so it using jQuery/javascript ????
<input type="checkbox" name="Dept" value="ALL"/>
<input type="checkbox" name="Dept" value="HR"/>
<input type="checkbox" name="Dept" value="FINANCE"/>
<input type="checkbox" name="Dept" value="IT"/>
<input type="checkbox" name="Dept" value="SALES"/>
Try this
jQuery > 1.6
// Cache the selectors as they are being multiple times
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
// Set the other inputs property to the all checkbox
$inputs.not(this).prop('checked', this.checked);
});
// Change event for all other inputs
$inputs.not($all).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
// Get the checked checkboxes
var $checked = $others.filter(function () {
return this.checked;
});
// If length is not equal then uncheck the All checkbox
if ($others.length !== $checked.length) {
$all.prop('checked', false);
}
});
jQuery 1.4.4
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
var allChk = this;
$inputs.each(function() {
this.checked = allChk.checked;
});
});
$inputs.not($('input[value=ALL]')).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
var $checked = $others.filter(function () {
return this.checked;
});
if ($others.length !== $checked.length) {
$all[0].checked = false;
}
});
jQuery > 1.6 Fiddle
jQuery 1.4.4 Fiddle
Try this,
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
where case is the class added to othe check boxes
For online demo visit,
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
DEMO
$('input[type="checkbox"][name="Dept"]').change(function () {
if (this.value == 'ALL') {
$('input[name="Dept"]').prop('checked', this.checked);
}
});
Updated Demo with jQuery 1.5.2
$('input[type="checkbox"][name="Dept"][value="ALL"]').change(function () {
$('input[name="Dept"]').attr('checked', this.checked);
});
$('input[type="checkbox"][name="Dept"]:gt(0)').change(function () {
if (!this.checked) {
$('input[name="Dept"][value="ALL"]').removeAttr('checked');
}
if ($('input[type="checkbox"][name="Dept"]:gt(0)').length == $('input[type="checkbox"][name="Dept"]:gt(0):checked').length) {
$('input[type="checkbox"][name="Dept"][value="ALL"]').attr('checked',true);
}
});
Here's one way to do it:
$(document).ready(function() {
var $cbs = $('input[name="Dept"]').click(function() {
if (this.value==="ALL")
$cbs.prop("checked", this.checked);
else if (!this.checked)
$cbs[0].checked = false;
});
});
Jawdroppingly good demo: http://jsfiddle.net/MNbDw/2/
Note that obviously my code above has a hardcoded assumption that the "ALL" checkbox will be the first one (at the point where I unchecked it using $cbs[0]). You could change the else if case to do this instead:
$cbs.filter('[value="ALL"]').prop("checked",false);
Demo: http://jsfiddle.net/MNbDw/3/
Or change your html to give that particular checkbox an id or whatever.
UPDATE: The .prop() method was introduced in jQuery 1.6. For version 1.5.2 (as mentioned in a comment) use .attr() instead as shown here (though 1.5.2 is so old that jsfiddle doesn't actually offer it as an option so I had to add it under "External Resources"): http://jsfiddle.net/MNbDw/9/

Enable button when checkboxes selected

I have multiple checkboxes and a submit button that is initially disabled. When checking a box the button is enabled and when unchecking, the button is disabled again.
If have multiple checkboxes selected but uncheck one, the button becomes disabled even though I have selected other checkboxes. How can I fix this issue?
<script type="text/javascript">
$(function() {
$(".checkbox").click(function() {
$(".delete").attr("disabled", !this.checked);
});
});
</script>
HTML
<input type="checkbox" name="msg[]" value="32" class="checkbox" />
<input type="checkbox" name="msg[]" value="44" class="checkbox" />
<input type="checkbox" name="msg[]" value="26" class="checkbox" />
<button type="submit" class="delete" disabled="disabled">Delete</button>
$(function() {
$(".checkbox").click(function(){
$('.delete').prop('disabled',$('input.checkbox:checked').length == 0);
});
});
Demo: http://jsfiddle.net/AlienWebguy/3U364/
Implement a counter to track how many are checked, rather than just disabling the button. Add 1 every time a box is checked, and subtract 1 every time a box is unchecked. Once the counter hits 0, disable the button. When it changes to 1, enable the button (if it changes to any higher number it will have already been enabled, so you don't need to enable it every time). Sample:
<script type="text/javascript">
var boxcounter;
$(function() {
boxcounter = 0;
$(".checkbox").click(function() {
if(this.checked) {
counter++;
if(counter == 1){
$(".delete").attr("disabled", "");
}
} else {
counter--;
if(counter == 0){
$(".delete").attr("disabled", "disabled");
}
}
}
}
</script>
Try this where I am basically checking if all the checkboxes are not checked then disable the button.
$(function() {
$(".checkbox").click(function() {
$(".delete").attr("disabled", !$(".checkbox:checked").length);
});
});
You need to check the state of the other boxes each time 1 box is toggled.
You can build an array of every checkbox.
Then, loop through testing for checked, and exit the loop on checked (this is what you care about).
If you reach the end of the loop and checked for all was false, then disable the button.
This will prevent one uncheck from disabling the button.
You're currently only checking "this" checkbox rather than all.
This code is Actually works without any error.
var boxcounter;
$(function() {
let boxcounter = 0;
$(".cgv-checkbox").click(function() {
if(this.checked) {
console.log('checked');
boxcounter++;
if(boxcounter == 3){
$("#register_form_Register").removeAttr("disabled");
}
} else {
boxcounter--;
if(boxcounter < 3){
$("#register_form_Register").attr("disabled", "disabled");
}
}
});
});
This will work with multiple checkboxes as well.

check/uncheck radio input with javascript

I have a radio input group. If a radio is checked and I click again it becomes unchecked.
Is there a way to get the previous status of the radio onClick event?
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
jQuery edition
// bind to retrieve old status
$('input[type="radio"]').mousedown(function() {
// if it was checked before
if(this.checked) {
// bind event to reset state after click is completed
$(this).mouseup(function() {
// bind param, because "this" will point somewhere else in setTimeout
var radio = this;
// apparently if you do it immediatelly, it will be overriden, hence wait a tiny bit
setTimeout(function() {
radio.checked = false;
}, 5);
// don't handle mouseup anymore unless bound again
$(this).unbind('mouseup');
});
}
});
But again, this is not how radio buttons are intended to be used. I think you'd be better of with a set checkbox'es where you could uncheck all other checkboxes than the current clicked (hence always max 1 selected)
A working example
I use this. You simply store the pre-click value and ! it into the value.
<input type=radio name="myoptions" value="1"
onmousedown="this.tag = this.checked;" onclick="this.checked = !this.tag;">
This behavior is not the expected one for radio buttons and I don't recommend it at all. Try to find another way of achieving this. Use another widget or another option to reset the field value:
http://jsfiddle.net/marcosfromero/rRTE8/
try this:
function resetMeIfChecked(radio){
if(radio.checked && radio.value == window.lastrv){
$(radio).removeAttr('checked');
window.lastrv = 0;
}
else
window.lastrv = radio.value;
}
<input value="1" name="options" checked="checked" type="radio" onClick="resetMeIfChecked(this)" />A
<input value="2" name="options" type="radio" onClick="resetMeIfChecked(this)" />B
<input value="3" name="options" type="radio" onClick="resetMeIfChecked(this)" />C
Its quite simple. Just follow the simple example and
var rdblength=document.formname.elementname.length;
alert('length='+rdblength);
for(i=0;i<rdblength;i++){
document.formname.elementname[i].checked=false;
}
Just find the length and make every index checked=true/false.
Ping me at:-
http://manojbardhan2009.blogspot.com
I had the same problem and figured it out. None of the answers above work exactly as I wanted - most of them require an additional button to reset the radio. The goal was to uncheck radio by clicking on the radio itself.
Here's the fiddle: http://jsfiddle.net/MEk5Q/1/
The problem was very complicated because the radio button value changes BEFORE the click event fires so when we're listening to the event we can't tell if the radio button was already checked or not. In both cases it is already checked.
Another approach was to listen to mousedown event. Unlike click, it fires before changing radio checked attribute but unchecking it inside event handler gives us nothing since it is checked back again during mouseup event.
My answer is a little ugly workaround so I generally don't suggest it to others and I'll probably abandon it myself. It works but it involves 20ms timeout function which I'm not fond of in cases like this.
Here is the code explanation:
$('input[type="radio"]').on('mousedown', function() {
if (this.checked) { //on mousedown we can easily determine if the radio is already checked
this.dataset.check = '1'; //if so, we set a custom attribute (in DOM it would be data-check="1")
}
}).on('mouseup', function() {
if (this.dataset.check) { //then on mouseup we determine if the radio was just meant to be unchecked
var radio = this;
setTimeout(function() {radio.checked = false;}, 20); //we give it a 20ms delay because radio checking fires right after mouseup event
delete this.dataset.check; //get rid of our custom attribute
}
});
As a timeout function I could use a string (less writing) but as far as I know it would be eval'ed. Though I don't trust eval function, I prefered anonymous function.
One more thing - one could ask why spreading the code into two separate event handlers while we can fire the timeout function on mousedown? Well, what if someone press the mouse on a radio and holds it for a few secs or even someone is simply a very slow person ;). Generally, with this solution we omit the problem of lag between mousedown and mouseup.
If you need some more info about dataset, here's the MDN reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
This property came with HTML5 and might be not cross-browser, I guess, so if you want 100% compatibility, replace it with any other solution that'll contain the data, you name it.
Sorry about jQuery here and there but I hope you're fine with it - it was much easier that way.
Hope you'll enjoy it.
$('input[type="radio"]').on("mousedown", function () {
if (this.checked) {
$(this).one("click", function () {
this.checked = false;
});
}
});
I was never too happy about being forced to aim at that tiny radio button, so I came up with a larger target AND a way to turn a radio group off without resorting to anything that would upset the HTML / JavaScript purists.
The technique relies on not molesting the radio buttons at all via event handlers, but checking for a readonly proxy for each one instead. Everything is contained in what's below in pure JavaScript using a radio group to select a type of cheese, or no cheese at all.
I purposely used no styling in this example to avoid that added layer. The dump button will tell you what the three checked states are, so use it to interrogate what happened after hitting the radio or text input elements. For example simplicity I used a global to remember the former state, but a more elegant method is to use a dataset, which I what I use in the real code of my application.
<!DOCTYPE html>
<html>
<head>
<title>Uncheck a radio button</title>
<script>
function attachEventListener(target, eventType, functionRef, capture) {
"use strict";
if (typeof target.addEventListener !== 'undefined') {
// Most modern browsers
target.addEventListener(eventType, functionRef, capture);
} else if (typeof target.attachEvent !== 'undefined') {
// IE
target.attachEvent('on' + eventType, functionRef);
} else {
eventType = 'on' + eventType;
if (typeof target[eventType] === 'function') {
var oldListener = target[eventType];
target[eventType] = function() {
oldListener();
return functionRef();
};
} else {
target[eventType] = functionRef;
}
}
}
</script>
</head>
<body>
<form>
<input id="Cheddar-radio" class="radio" type="radio" name="Cheeses-0" value="Cheddar Cheese" tabindex="-1"></input>
<input id="Cheddar-text" type="text" readonly value="Cheddar Cheese" tabindex="-1"></input><br>
<input id="Swiss-radio" class="radio" type="radio" name="Cheeses-0" value="Swiss Cheese" tabindex="-1"></input>
<input id="Swiss-text" type="text" readonly value="Swiss Cheese" tabindex="-1"></input><br>
<input id="American-radio" class="radio" type="radio" name="Cheeses-0" value="American Cheese" tabindex="-1"></input>
<input id="American-text" type="text" readonly value="American Cheese" tabindex="-1"></input><br><br>
<input onclick="dumpStates()" type="button" name="button" value="dump" tabindex="-1"></input>
</form>
<script>
window.onload = addRadioListeners;
function addRadioListeners() { // But do it on the -text elements.
attachEventListener(document.getElementById('Cheddar-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('American-text'), 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Cheddar-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('American-text'), 'mouseup', checkNewState, false);
}
function dumpStates() {
console.log(document.getElementById('Cheddar-radio').checked +
' ' + document.getElementById('Swiss-radio').checked +
' ' + document.getElementById('American-radio').checked);
}
var elementWasChecked; // Global - Could just as well use a dataset attribute
// on either the -radio or -text element and check it instead.
function rememberCurrentState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
elementWasChecked = radioElement.checked;
radioElement.checked = true;
}
function checkNewState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
var currentState = radioElement.checked;
if (elementWasChecked === true && currentState === true) {
console.log('Changing ' + radioElement.id + ' to false.');
radioElement.checked = false;
}
};
</script>
</body>
</html>
If you click on the radio buttons they work as expected. If you click on the text items next to each, they are a proxy for the radio buttons with one exception. If you click on a text item that has an associated radio button that's already checked, it will uncheck it. Therefore, the text proxy's are event triggered, and not the radio buttons.
The added benefit is that you can now hit the larger text target too.
If you want to make it simple and wouldn't mind using a double-click event try something like this:
<input name="options" type="radio" ondblclick="this.checked=false;">
#jerjer's answer is almost perfect, but radios can be switched also by arrows if the radio group has the focus (so mousedown event is not enough). Alas, the radio group also gets checked when activated by focus shift (Tab), which can undesirably check one option. Therefore space should uncheck the focused radio, just like the checkbox behavior.
This code fixes that for all radios (Most credit still goes to jerjer):
window.addEventListener("DOMContentLoaded", function() {
var radios = document.querySelectorAll("input[type=radio]");
for(var i=0; i<radios.length; ++i) {
radios[i].addEventListener("click", function(e) {
if(e.target.checked && e.target.value == window.lastrv){
e.target.checked = false;
window.lastrv = 0;
}
else
window.lastrv = e.target.value;
});
radios[i].addEventListener("keypress", function(e) {
if(e.keyCode==32) e.target.click();
});
}
});

Categories