HTML radio and checkboxes not checking/unchecking internally - javascript

So visually they have the correct behavior. Only 1 radio button in a set is checked and the checkbox checks/unchecks in reaction to pressing it but it seems when checking the status of the inputs in the console that isn't the case. So I have:
<input id="addon-fixed" type="checkbox" value=True checked />
<input id="addon-type0" name="addon-type" type="radio" checked/>Addon<br>
<input id="addon-type1" name="addon-type" type="radio"/>Cutout
But regardless of what I click the behavior is always the same
$('#addon-fixed').attr('checked') // always there
$('#addon-type0').attr('checked') // always there
$('#addon-type1').attr('checked') // always undefined

Use prop() instead of attr()
$('#addon-fixed').prop('checked')
Checking or unchecking the checkbox changes the checked property, it doesn't change the element's attribute.

if you want to check whether it is checked or not:
Use this...
if($('#addon-fixed').is(':checked')){
//checked
}else {
//unchekced
}
hope this will help you...

Related

How do i uncheck radio button in one click

I have the code to uncheck radio button, but the problem is, its not happening in one click when the radio button is checked, I am fetching the value of radio button as checked from mysql, so the default value of radio button is checked and when I click on the radio button the value should uncheck upon single click but my code is making it happen on double click. How do I make it happen with single click?
var check;
$('input[type="radio"]').hover(function() {
check = $(this).is(':checked');
});
var checkedradio;
function docheck(thisradio) {
if (checkedradio == thisradio) {
thisradio.checked = false;
checkedradio = null;
}
else {checkedradio = thisradio;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="check" value="check" onClick="javascript:docheck(this);" checked="checked"/>
Radios by design are meant to be used in a group (https://html.spec.whatwg.org/#radio-button-state-(type=radio)) - a group of 2 or more radios should form a group to allow the user to pick a value from the selection in that group. By design the radio group behaviour is this - once a selection is made (either by the user or programatically), that choice sticks, and there is no way to undo it, other than choose another radio option from the group. You'll see in your example, that without the JavaScript bit, if you by default uncheck the radio, then check it manually, you won't be able to uncheck it again. This is how it's supposed to work.
The rule of thumb should be that solving a problem on the backend should not come at the expense of the front-end, as it negatively impacts the user-experience, and will cause problems to the user. If you for any reason HAVE TO stick with such a bad UX solution, here is a way to hack your radio to act like a checkbox, but it is seriously not advised, and you should change your backend to use checkboxes instead.
Here is the radio hack (and a native checkbox input that should be used instead):
var myRadio = $('input[type="radio"]:checked');
myRadio.on('click', function() {
if (myRadio.attr('checked')) {
myRadio.removeAttr('checked');
myRadio.prop('checked', false);
} else {
myRadio.attr('checked', 'checked');
myRadio.prop('checked', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>This works, but it's bad UX, so avoid!</b><br>
<input type="radio" name="check" value="check" checked />
<hr>
<b>Use this instead!</b>
<br>
<input type="checkbox" name="real-check" value="real-check" checked />
You'll see that the jQuery selector is deliberately set to only pick the "checked" radio, so the JavaScript solution only takes over the native behaviour if the radio is checked by default. As soon as the radio is not checked by default, you'll see how the browser forces your selection once it's checked manually - this is a tell tale sign that you're trying to deviate from the expected behaviour.
You'll also see that the checkbox natively works - without the need for JavaScript or jQuery.
RobertP raised an interesting point about the user experience, or in IT-talk: "UX". In some cases it is mandatory that a single option needs to be clicked. This is exactly what radio buttons were made for. However, I have come across cases, where a "none" selection should also be offered. For these cases you could simply supply an extra radio button with the option "none" OR you could make the radio buttons "unselectable" again. This seems to go against the intended radio button behaviour. However, as it is possible to start out with no radio buttons being selected, why should it not be possible to return to this state after, maybe, the user had clicked on an item prematurely?
So, with these considerations in mind I went ahead and put together a way of doing what OP had in mind. I extended the example a little bit by including further radio button options:
$.fn.RBuncheckable=function(){ // simple jQuery plugin
const rb=this.filter('input[type=radio]'); // apply only on radio buttons ...
rb.each(function(){this.dataset.flag=$(this).is(':checked')?1:''})
.on('click',function(){
if (this.dataset.flag) $(this).prop('checked',false) // uncheck current
// mark whole group (characterised by same name) as unchecked:
else rb.filter('[name='+this.name+']').each(function(){this.dataset.flag=''});
this.dataset.flag=this.dataset.flag?'':1; // invert flag for current
});
return this;
}
$('input').RBuncheckable(); // apply it to all radio buttons on this page ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Two groups of radio buttons with "uncheck" option:</h4>
<input type="text" value="This input field is unaffected">
<p>group one:</p>
<label><input type="radio" name="check" value="a" checked /> Option A</label><br>
<label><input type="radio" name="check" value="b"/> Option B</label><br>
<label><input type="radio" name="check" value="c"/> Option C</label>
<p>group two:</p>
<label><input type="radio" name="second" value="d"/> Option D</label><br>
<label><input type="radio" name="second" value="e"/> Option E</label><br>
<label><input type="radio" name="second" value="f" checked/> Option F</label>
In the .each() loop I collect the initially checked state for all selected radio buttons. I store the individual checked state in a data attribute "flag" for each radio button.
The click event handler function then picks up this data flag and decides whether to step into action by either removing the checked state from the current element or simply resetting the flag data-attributes for the whole group (characterised by having the same name as the currently clicked one). In a last operation it then inverts the flag state for the current element again. As all data attributes are stored as strings, the values 1 and "" are "truthy" and "falsy" values that can be directly tested.
This results in exactly the behaviour you were looking for. I hope ;-)
By having the functionality packaged in a little jQuery plugin it can now be applied to any jQuery object directly.

ko binding for checkbox: change 'checked' attr from code not change the observable field

I have checkbox at html that is binding to observable-field (field of breeze entity).
<input id="chk1" type="checkbox" data-bind="checked: data().isBirthday"/>
The binding works well from the tow sides:
When I write at code:
data().isBirthday(true);
the checkbox become checked.
and when I write at code
data().isBirthday(false);
the checkbox become unchecked.
And when I choose the checkbox by clicking with mouse - the observable field gets value of true. (Or when I unchecked by mouse - it gets value of false).
sometime, I need to change the checked attribute of the checkbox by code, specifically by retrive checkbox with jquery.
(I cannot do it by the observable field becouse of any reasons).
I do:
var control = $('#chk1')[0];
control.checked = false;
but this not change the value of the binded observable-field. It continue holding true value.
I tried to triiger the change event:
$(control).change()
It didn't help.
So, what should I do?
Here is an example:
https://jsfiddle.net/kevinvanlierde/72972fwt/4/
Can we see the html code?
Try $('#chk1').prop("checked", false);

Bootstrap: how to check if an elment is checked and set it to disable if checked

This code works great but is missing something I need.
Basically if the input has a checked="checked" attribute, it should keep the other two elements disabled. if it is not checked the elements are enabled.
Here's my code on jsFiddle: http://jsfiddle.net/arunpjohny/gMgm7/1/
And this would be my input
<input class="test_priv1" type="checkbox" name="custom" id="custom" checked="checked" onclick="" />
I guess this would be translated to:
If my input gets a check, disable the other two elements. If my input has the checked="checked" then keep my other two elements disabled. If my input is unchecked enable the two elements.
Got it working:
$(document).ready(function() {
if ($('.test_priv1').is(':checked')){
$('.test_priv2, .test_priv3').prop('disabled',true);
}
$('.test_priv1').change(function () {
if(this.checked){
$('.test_priv2, .test_priv3').prop('disabled',true);
}else{
$('.test_priv2, .test_priv3').removeAttr('disabled');
}
});
});
Here's a demo
#Dan had it right with checking on ready, but for some reason running .checked off the element does not seem to work. However, if you use $('.test_priv1').is(':checked') then it seems to work properly. See this fiddle for an example of it working on both page load and on change.

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Checking a radio button in JQuery

I need to programmatically check a radio button given its value. The form has an id and the input type obviously has a name (but no id). The only code I managed to get working so far is:
$('input[name=my_name]:eq(1)').attr('checked', 'checked');
But I'd like to be able to check it by explicitly providing the value.
So you want to select the radio which has a particular value:
$('input[name=my_name][value=123]').attr('checked', true); // or 'checked'
Below code worked with me, if I am assigning an ID to the radio button:
<input type="radio" id="rd_male" name="gender" value="Male" />
<input type="radio" id="rd_female" name="gender" value="Female" />
$('#rd_male').prop('checked', true);
You should use prop instead of using attr . It's more recommended
$('input[name=my_name][value=123]').prop("checked",true)
In order to select the radio button programmatically, you can call a jQuery trigger or
$(".radioparentclass [value=radiovalue]")[0].click();
$('input[name=field]:eq(1)').click();
Note : field = radio button name property
Recommend use .click()
The other solution that only change radio option property or attribute
will NOT trigger radio event, you have to manually call radio event.
$("#your_radio_option_ID_here").click()

Categories

Resources