How can I toggle a radio button's checked state with jQuery? - javascript

As can be seen here, I've got this HTML:
<input type="radio" id="radbtnEmp" >rad btn</input>
...and this jQuery:
$('#radbtnEmp').click(function () {
alert("radbtnEmp clicked");
});
The alert does display when I click the radio button; However, clicking the radio button a second time does not toggle its state back to unchecked. How can I do that in jQuery?
I want to be able to respond to its state like this (or something similar):
if ($('#radbtnEmp').attr('checked', true)) {
// do stuff
} else {
// do other stuff
}
...but if the radiobutton is never checked/false, that doesn't work.

the radio buttons cannot be checked and unchecked..
For that you need to use checkboxes:
Html:
<input type = "checkbox" id = "myCheckBox">I am CheckBox</input>
jQuery:
$('#myCheckBox').on('click', function() {
if ($('#myCheckBox').is(':checked')) {
// code
}
else {
// code
}
})
Hope this helps

Related

Show message when radio button selected

I am trying to get the following to work without much success
$(document).ready(function()
{
$('#shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a').click(function()
{
alert("Please ensure you have selected the correct option");
});
});
</script>
Using inspect on Chrome, I looked for the ID for the radio button and found shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a but even so, when I save the javascript and load the page and click the radio button, no message is displayed.
The code I used to find the ID in inspect was as follows:
<input name="shippingOptionIds.5ed62ea40135a" class="form-checklist-checkbox optimizedCheckout-form-checklist-checkbox" id="shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a" type="radio" value="7dac01c2c834210be865275f0700a45a">
you have to add an event (type input not click) to the radio and then add condition if the input.checked === true then show message
// select radio input
const input = document.getElementById('input');
// add event on input
input.addEventListener('input', () => {
if (input.checked) {
alert('this is a message!');
}
});
<input type="radio" id="input">

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

jQuery/Javascript Checkbox

i want do something like this with a checkBox. if the user clicks on the checkbox, it should change its state (checked -> unchecked and vv. ).
my code:
$('#checkBoxStandard').change(function() {
clickedFormBoxen('standard');
});
function clickedFormBoxen(active){
if(active == 'standard'){
if( $('#checkBoxStandard').is(":checked")){
$('#checkBoxStandard').prop("checked", false);
}else{
$('#checkBoxStandard').prop("checked", true);
}
console.log('ac: '+$('#checkBoxStandard').is(':checked'));
}
Unfortunately, the checkbox will not be unchecked again. The fist time, the checkbox is getting checked, but if i click on it again, nothing happens, it's still checked.
I wish to use this code so i can change the state of the checkbox by function call and not just by user interaction.
Please help me and sorry for my english^^
Try
$('#checkBoxStandard').removeAttr("checked");
You mean something like this? (jsFiddle)
HTML
<input type="checkbox" id="checkbox">
<label for="checkbox">Hey,check me!</label>
JavaScript
var respond = true;
function manualCheck(state)
{
respond = false;
$('#checkbox').prop("checked", state);
}
$('#checkbox').change(function ()
{
if (!respond)
{
respond = true;
return;
}
// Your code
}
As i've mentionend in my comment to your question, with your function clickedFormBoxen you effectively revert the effect of a user interaction on the checkbox element. Thus it seems that you have to call the change handler from a click handler on your checkbox element (i've streamlined the code a bit):
function clickedFormBoxen(active) {
if (active == 'standard') {
$('#checkBoxStandard').prop("checked", !($('#checkBoxStandard').prop("checked")));
}
}
$(document).ready( function(){
$('#checkBoxStandard').change( function(e) {
clickedFormBoxen('standard');
1;
});
$('#checkBoxStandard').click(function(e) {
$('#checkBoxStandard').change();
1;
});
});

Javascript/ JQuery Deselecting radio buttons

I have the following javascript, which I want to use to enable the user to deselect a selected radio button by clicking it. (I know this is not standard, but it is required by the system :)
DeselectRadioButton = {
setup: function () {
$(".deselectRadioButton").click(function () {
if ($(this).is(':checked')) {
alert("I am checked!");
($(this).removeAttr('checked'));
}
});
}
};
My issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.
I guess I am receiving the event after the item has changed - how can I fix this code to make my radio button deselectable?
Thanks!
However, the main issue is that when I
select an unselected radio button, it
immediately deselects it after the
alert shows.
It seems you can't prevent the default behavior of a radio button with either return false or e.preventDefault() as the radio button always is checked when the click handler is fired. One way around this was to add a separate class to the radio button and use that as your indicator.
$(".deselectRadioButton").click( function(e){
if($(this).hasClass("on")){
$(this).removeAttr('checked');
}
$(this).toggleClass("on");
}).filter(":checked").addClass("on");
Code example on jsfiddle.
One of the challenges I found while doing this was with groups of radio buttons. The solutions provided work splendidly for a single radio button, but in groups I ran into an issue where de-selecting one and then trying to select another failed (until a second click).
I just came across a solution here that's working splendidly:
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent = function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck = function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val){
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
try:
$(this).removeAttr('checked');
I experienced the same problem David described with groups of radio buttons. Here's another way around that problem (based on Mark's solution) that works for multiple radio button groups on the same page:
$(":radio").click( function(e){
var itsOn = $(this).hasClass("on");
$(":radio[name="+ this.name + "]").removeClass("on");
if(itsOn){
$(this).removeAttr('checked');
$(this).siblings().filter("[value='']").attr('checked', true);
} else {
$(this).addClass("on");
}
}).filter(":checked").addClass("on");
Are you sure there's nothing else messing with it?
I tried this code, and it works:
HTML
<ul>
<li>
<input id="one" name="value" type="radio">
<label for="one">One</label>
</li>
<li>
<input id="two" name="value" type="radio">
<label for="two">Two</label>
</li>
<li>
<input id="three" name="value" type="radio">
<label for="three">Three</label>
</li>
</ul>
JavaScript
$("input[type='radio']").click(function(event) {
// If the button is selected.
if ($(this).hasClass("checked")) {
// Remove the placeholder.
$(this).removeClass("checked");
// And remove the selection.
$(this).removeAttr("checked");
// If the button is not selected.
} else {
// Remove the placeholder from the other buttons.
$("input[type='radio']").each(function () {
$(this).removeClass("checked");
});
// And add the placeholder to the button.
$(this).addClass("checked");
}
});
You can test it here.

I need an event trigger for a radio button for when it is unchecked because another button is checked

I need an event trigger for a radio button for when it is unchecked because another button is checked.
The code below should demonstrate my dilemma.
If you will notice, there is an onchange event trigger atttached to each radio button and checkbox in the html code. In theory a change in state from checked to unchecked should fire the onchange event.
This happens as expected with the check boxes. If you check one, you get the alert, 'Your item is changed to checked'. If you uncheck it, you get the alert, 'Your item is changed to unchecked'.
With the radio buttons, when you check button one, you get, as expected, the alert, 'Your item is changed to checked' since the button changed from unchecked to checked. However, when you check the second button and the first radio button is changed from checked to unchecked the "onchange" event trigger does not fire and the 'else' alert is not triggered.
So this issue for me is what event is triggered when a radio button gets unchecked by another button being checked?
I appreciate everyone's assistance on this.
--Kenoli
<html>
<head>
<title></title>
<script type="text/javascript">
function clickAction() {
//alert ('Your item changed');
if (this.checked == true) {alert ('Your item is changed to checked');}
else if (this.checked == false) {alert('Your item is changed to unchecked');}
}
</script>
<script type="text/javascript">
function initializeToggles() {
var button1= document.getElementById('button1');
button1.onchange = clickAction;
var box1= document.getElementById('box1');
box1.onchange = clickAction;
var box2= document.getElementById('box2');
box2.onchange = clickAction;
}
</script>
<script type="text/javascript">window.onload = initializeToggles;</script>
</head>
<body>
<input type="radio" name="testRadio" id="button1" >Button one<br/>
<input type="radio" name="testRadio" id="button2" >Button two<br/><br/>
<input type="checkbox" name="testCheckbox" id="box1" >Box one<br/>
<input type="checkbox" name="testCheckbox" id="box2" >Box two<br/><br/>
</body>
</html>
I came here looking for a quick solution for this type of problem, and nuc's answer helped me come up with this:
$(document).ready(function(){
$('input[type=radio]').change(function() {
var selected = $(this);
$('input[type=radio]').each(function() {
if $(this).attr('id') != selected.attr('id') {
console.log( $(this).attr('value') + ' was deselected because ' + selected.attr('value') + ' was clicked.')
}
});
});
});
There is no event for when a radio button gets unchecked. You might be able to use the onpropertychange event, however that's not a standardised event so it might only work in Internet Explorer.
The safest way would be to take care of that in the onchange event. If you want to know which radio button was unchecked, you would have to keep a reference to the currently checked element in a variable.
I slightly modified rthbound's code to handle a group of radio input's, in my case enclosed in a <table>. But this could easily altered for a <div>. Also this code is more compliant with jQuery 1.9. A common class would be better, to take the class from the selected radio and find other radio inputs with the same class, but I'm working with ASP.NET and this is quicker and easier for me.
$(document).ready(function(){
$(document).on("change", "input[type='radio']", function () {
var selected = $(this);
$(this).closest("table").find("input[type='radio']").each(function () {
if ($(this).attr("id") !== selected.attr("id")) {
console.log($(this).attr("value") + " was deselected because " + selected.attr("value") + " was clicked.");
}
});
});
});
I've solved this issue in a generic way:
whenever a radio button is changed:
if they were triggered by this system - we don't want unending loops.
find all its radio button friends
trigger change on them
then I can test for whether the radio button was checked or unchecked.
$(function(){
$('body').on('change', 'input[type="radio"]', function(e, by_other) {
if (!by_other) {
$("input[type='radio'][name='" + $(this).attr('name') + "']")
.not(this)
.trigger('change', true)
}
}
}
(I did translate it from coffeescript to javascript for ya'll.)
The Radio buttons have same name, so we can select them by name.
Because .change() is not effected when the radio is unchecked, so we use .click() instead of.
$('input[name="your-radio-name"]').click(function() {
var $radios = $('input[name="your-radio-name"]');
for (var i = 0; i < $radios.length; i++) {
var radio = $radios[i];
if (radio != this) {
radio = $(radio);
// Process for unchecked radios here
}
}
// Now, process for checked radio
// alert(this.value + ' is checked'); Or
alert($(this).val() + ' is checked');
});

Categories

Resources