How to toggle HTML radio button with jQuery? - javascript

I have a radio button that is checked by default. What I am trying to accomplish is just to toggle it on/off with a click and simple logic but I do not understand what I'm doing wrong.
Here is my HTML:
<input type="radio" id="member" name="member" value="member" checked>
<label for="member" >Member Reported</label>
And here is my jQuery:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
}
})
This works great, but I noticed that it's not changing the DOM once clicked, and furthermore, when I try to add the prop to true (like below), it's not checking back on the GUI.
Here's the DOM:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
} else if (!$('#member').is(':checked')) {
$('#member').prop('checked',true)
}
})

How about this? Is this what you are willing?
$('#member + label').click((e) => {
console.log($('#member')[0].checked);
if($('#member')[0].checked) {
$('#member')[0].checked = false;
} else{
$('#member')[0].checked = true;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" name="member" value="member" checked >
<label for="" >Member Reported</label>

As long checked exist in element, it will stay checked. You will have to remove it via jquery to make it work.
You can check functioning here.
<input type="radio" checked>
<br>
<input type="radio" checked="true">
<br>
<input type="radio" checked="false">
<br>
<input type="radio">

I think that's the way it should be.
$('.radios').click((e) => {
$('.radios').each(function (i) {
$(this).removeAttr('checked')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" class="radios" name="member" value="member" >
<label for="member" >Member Reported</label><br/>
<input type="radio" id="member2" class="radios" name="member" value="member" >
<label for="member2" >Member Reported2</label><br/>
<input type="radio" id="member3" class="radios" name="member" value="member" checked>
<label for="member3" >Member Reported3</label><br/>

Related

Can a radio button in a form be used to select another radio button in the same form?

I have a HTML form that has 2 groups of radio buttons. I need the first group to also change the selection on the second group, i.e.
Group 1 has options A & B, Group 2 has options C & D;
when I select A, I need the form to also select C; when I select B, I need the form to also select D.
I need A & C selected by default when the page loads.
A & C will always be paired; B & D will always be paired.
I know this sounds impractical, but the reason is that this form is sending its responses to another provider's form where I can't edit the fields. They have effectively got a duplicate question in their form (same question just slightly different wording), and I don't want my users to have to answer the same question twice, so I would hope to hide the buttons for C & D from view.
The "name" on the each group is different, and the "value" & "id" for each radio button is unique.
Can this be done? JQuery & JS solutions are welcome.
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<label class="label-text" for="buyer">Buyer</label>
<input type="radio" name="agent" id="buyer" value="false">
<label class="label-text" for="agent">Agent</label>
<input type="radio" name="agent" id="agent" value="true">
Simply set the checked property of the corresponding button.
document.getElementById("buyer").checked = true;
document.getElementById("buyer-select").addEventListener("click", function() {
document.getElementById("buyer").checked = true;
});
document.getElementById("agent-select").addEventListener("click", function() {
document.getElementById("agent").checked = true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<br>
<label class="label-text" for="buyer">Buyer</label>
<input type="radio" name="agent" id="buyer" value="false">
<label class="label-text" for="agent">Agent</label>
<input type="radio" name="agent" id="agent" value="true">
You can also replace the second set of radio buttons with a single hidden input. Put the values that would have been sent by the radio button into the value of the hidden input.
document.getElementById("buyer-select").addEventListener("click", function() {
document.getElementById("buyer-agent").value = "false";
});
document.getElementById("agent-select").addEventListener("click", function() {
document.getElementById("buyer-agent").value = "true";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<input type="hidden" name="agent" id="buyer-agent" value="false">
Is this what you wanted:
If yes, try this code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
$('input[type=radio][name="pet"]').change(function() {
var $radiobutton = $("input[value='"+$(this).val()+"']");
$radiobutton.prop("checked", true);
});
$('input[type=radio][name="pet2"]').change(function() {
var $radiobutton = $("input[value='"+$(this).val()+"']");
$radiobutton.prop("checked", true);
});
}, false);
</script>
</head>
<h2>Select a Pet</h2>
<div>
<input name="pet" type="radio" value="dog" /><span>Dog</span>
<input name="pet" type="radio" value="cat" /><span>Cat</span>
<input name="pet" type="radio" value="fish" /><span>Fish</span>
</div>
<div>
<input name="pet2" type="radio" value="dog" /><span>Dog</span>
<input name="pet2" type="radio" value="cat" /><span>Cat</span>
<input name="pet2" type="radio" value="fish" /><span>Fish</span>
</div>

how to uncheck a group of radio buttons when one in another group is checked

I have 2 groups of radio buttons. When a button in on group is clicked any button in the other group should be unchecked, and vice versa.
I tried below which works only once.
The smartest way I thought would be click(). But I can't get my head around it. Any suggestions?
function uncheckRadioBtnSet(){
if ($('[name="a"]').is(':checked')){
$('input[name="b"]').removeAttr('checked');
$(this).off('click');
}else{
$('input[name="a"]').removeAttr('checked');
$(this).off('click');
}
}
$("input[name='a']").click(function(){
uncheckRadioBtnSet();
});
$("input[name='b']").click(function(){
uncheckRadioBtnSet();
});
<input type="radio" name="a" value="1"><br>
<input type="radio" name="a" value="2"><br>
<input type="radio" name="a" value="3"><br>
<h6> separator </h6>
<input type="radio" name="b" value="4"><br>
<input type="radio" name="b" value="5"><br>
<input type="radio" name="b" value="6"><br>
Try this nanocode :)
$("input[name='a'], input[name='b']").click(function(){
$('input[name="'+{b: 'a',a: 'b'}[this.name]+'"]').prop("checked", false);
});
Plunker
Updated code according to new requirements
$("input[name='item_meta[313]'], input[name='item_meta[314]']").click(function(){
$('input[name="'+{'item_meta[313]' : 'item_meta[314]', 'item_meta[314]' : 'item_meta[313]'}[this.name]+'"]').prop("checked", false);
});
However, for the sake of readability, you can also write this code as:
var obj = {
'item_meta[313]' : 'item_meta[314]',
'item_meta[314]' : 'item_meta[313]'
}
$("input[name='item_meta[313]'], input[name='item_meta[314]']").click(function(){
$('input[name="'+obj[this.name]+'"]').prop("checked", false);
});
See this updated Plunker
You can use this:
$("input[name='a']").click(function(){
$('input[name="b"]').prop("checked", false);
});
$("input[name='b']").click(function(){
$('input[name="a"]').prop("checked", false);
});
Demo: https://jsfiddle.net/iRbouh/xn61vs1q/
it will be ok if we use same name for all radio buttons
<input type="radio" name="a" value="1"><br>
<input type="radio" name="a" value="2"><br>
<input type="radio" name="a" value="3"><br>
<h6>
separator
</h6>
<input type="radio" name="a" value="4"><br>
<input type="radio" name="a" value="5"><br>
<input type="radio" name="a" value="6"><br>

weird bug on radio buttons when change [duplicate]

This question already has answers here:
jquery attr('checked','checked') works only once
(2 answers)
Closed 6 years ago.
i'm trying to do a radio button with 2 options: yes and no (is a long form), but in this piece, i need that radio called refused or accomplished be checked when the user choose yes or no, refused and accomplished buttons already are disabled, the user can't change this manually.
1 - when user choose yes: accomplished must be checked
2 - if user choose no, refused must be checked.
3 - if user change the yes to no, or no to yes option we back to the rules 1 or 2 above.
however, i'm stuck because when i change the option the radio button change only once. and nothing happens after that.
this is my code right now: https://jsfiddle.net/bw21cxo5/1/
HTML:
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
js: (jquery 2.2)
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').attr('checked', true);
$('#accomplished').attr('checked', false);
} else {
$('#accomplished').attr('checked', true);
$('#refused').attr('checked', false);
}
});
You can associate the checkboxes with each other. Something like this using the data attribute would work:
Updated HTML
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes" data-partner="accomplished">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no" data-partner="refused">No
</label>
JavaScript
$('input[name="radio1"]').on('change', function() {
$('input[name="radio2]').prop('checked',false);
$('#'+$(this).data('partner')).prop('checked',true);
});
JS Fiddle: https://jsfiddle.net/igor_9000/bw21cxo5/3/
Hope that helps!
Your code works enough, only a little fix:
$(function () {
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').prop('checked', true);
} else {
$('#accomplished').prop('checked', true);
}
});
});
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<div>
<label for="yes">
<input type="radio" name="radio1" value="yes" id="yes" class="option-yes">Yes
</label>
<label for="no">
<input type="radio" name="radio1" value="no" id="no" class="option-no">No
</label>
</div>
<br><br>
<div>
<label for="refused">
<input type="radio" name="radio2" id="refused" disabled> Refused
</label>
<label for="accomplished">
<input type="radio" name="radio2" id="accomplished" disabled> Accomplished
</label>
</div>
It's better to use plain JS when checking radio buttons.
Try this:
$('input[name="radio1"]').on('change', function() {
if ($(this).hasClass('option-no')) {
$('#refused').get(0).checked = true;
} else {
$('#accomplished').get(0).checked = true;
}
});
The problem with your code is instead of attr you should have used prop. Here is the difference between them.
Demo

Radio button change events and improving similar functions

I'm looking for a smarter way to reuse functions with a similar purpose. For example I would want to change different radio buttons that toggle a hide class on different divs.
JSFiddle Link
How would you mathe JQuery to a reusable function,
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" checked class="eOne">Yes
<input type="radio" name="one" value="no" class="enBg">No</form>
<form>
<label>Enable Two</label>
<input type="radio" name="two" value="yes" checked class="eTwo">Yes
<input type="radio" name="two" value="no" class="enBrand">No</form>
<form>
<label>Enable Three</label>
<input type="radio" name="three" value="yes" checked class="eThree">Yes
<input type="radio" name="three" value="no" class="enS">No</form>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
div {
width: 100px;
height: 100px;
}
.one {
background: red;
}
.two {
background: green;
}
.three {
background: blue;
}
.hide {
display: none;
}
$(".eOne").change(function () {
$('.one').toggleClass("hide");
});
$(".eTwo").change(function () {
$('.two').toggleClass("hide");
});
$(".eThree").change(function () {
$('.three').toggleClass("hide");
});
Also, for some reason, in the demo (but not in my live version) the change function doesn't toggle the class unless I click no and then yes.
use classes for your html:
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" class="one" checked />Yes
<input type="radio" name="one" value="no" class="one" />No
</form>
<form>
<label>Enable Two</label>
<input type="radio" name="two" value="yes" class="two" checked />Yes
<input type="radio" name="two" value="no" class="two" />No
</form>
<div class="one"></div>
<div class="two"></div>
write functions for your javascript:
/*
* Bind a change event handler to a radio-input
* #param cls - selector string to input AND to-change div
*/
function bindChangeHandler(cls) {
$('input.' + cls).change(function () {
var element = $(this),// get Input element
name = element.val(), // get Input element name
is_checked = element.prop('checked'); // get state of radio box
// return if a deselect triggered the event (may be unnecessary)
if (!is_checked) return;
// change class of div-box according to checked radio-box
if (name == 'yes') {
$('div.' + cls).removeClass('hide');
} else {
$('div.' + cls).addClass('hide');
}
});
}
$(document).ready(function(){
bindChangeHandler('one');
bindChangeHandler('two');
});
HTML
<form>
<label>Enable One</label>
<input type="radio" name="one" value="yes" class="eOne" checked>Yes
<input type="radio" name="one" value="no" class="enBg">No
<br /><label>Enable Two</label>
<input type="radio" name="two" value="yes" checked class="eTwo">Yes
<input type="radio" name="two" value="no" class="enBrand">No
<br /><label>Enable Three</label>
<input type="radio" name="three" value="yes" checked class="eThree">Yes
<input type="radio" name="three" value="no" class="enS">No
</form>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
I haven't changed any of your CSS but changed your Javascript code. Have a look at this.There is no need to use the class .hideclass as we have already an inbuilt method for this. the toggle() method. if you want it to hide as soon as you click the radio button then just change all the toggle() to toggle(50). This change will hide the div boxes in just 50 milli seconds.
$("input[name='one']").change(function(){
$(".one").toggle();//add a number in toggle method to have a small animation effect :)
});
$("input[name='two']").change(function(){
$(".two").toggle();
});
$("input[name='three']").change(function(){
$(".three").toggle();
});
I have also updated the code on js fiddle. May be this is helpful for you :)
I like cbergmiller's answer. Here is the same rewritten with a callback allowing a more general use:
function hide(cls, name) {
// change class of div-box according to checked radio-box
if (name == 'yes') {
$('div.' + cls).removeClass('hide');
} else {
$('div.' + cls).addClass('hide');
}
}
/*
* Bind a change event handler to a radio-input
* #param cls - selector string to input AND to-change div
*/
function bindChangeHandler(cls, callback) {
$('input.' + cls).change(function () {
var element = $(this),// get Input element
name = element.val(); // get Input element name
callback(cls, name);
});
}
$(document).ready(function(){
bindChangeHandler('one', hide);
bindChangeHandler('two', hide);
});

OnClick of RadioButton not working

I was trying to change the text of a submit button on change of radio button .My code for html part is :
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment1" value="Yes"/>
<label for="segment1" id="controls">
<span class="ui-btn-text-controls">Yes</span>
</label>
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment2" value="No" checked="checked"/>
<label for="segment2" id="controls">
<span class="ui-btn-text-controls">No</span>
</label>
<input type="submit" value="send" name="sendbutton" id="sendbutton"/>
My javascript code is as follow :
function check(){
var x;
x=document.f1.radio-view;
if(x[0].checked){
document.f1.sendbutton.value="PROCEED";
}
else if(x[1].checked){
document.f1.sendbutton.value="SEND";
}
}
But its not changing the test.What can be the reason for it?
If you decide to address elements directly, use their names properly:
var x = document.f1['radio-view'];
... as you cannot access with the dot syntax the properties which names are not valid identifiers. document.f1.radio-view is treated as document.f1.radio - view, which apparently makes no sense.
But actually, I'd rather skip this part completely: if radio-button is clicked, it's definitely set as checked. So this...
<input type="radio" onclick="check(this)" ... />
...
function check(button) {
document.f1.sendbutton.value = button.value === 'Yes' ? 'PROCEED' : 'SEND';
}
... should be quite enough, as this demo shows.
See Demo here: http://jsfiddle.net/Tngbs/
//HTML
<form>
<fieldset id="SPserviceStatus" data-role="controlgroup" data-type="horizontal" data-mini="true">
<legend>Group<span class="required">*</span></legend>
<input type="radio" name="ss" id="s1" value="Yes">
<label for="serviceStatus1">Yes</label>
<input type="radio" name="ss" id="s2" value="No" checked="checked">
<label for="serviceStatus2">No</label>
</fieldset>
<input type='submit' id='submitBtn' value='SUBMIT' />
</form>
//JS
$("#s1").click(function () {
document.getElementById("submitBtn").value = "Yes Clicked";
return false;
});
$("#s2").click(function () {
document.getElementById("submitBtn").value = "No Clicked";
return false;
});

Categories

Resources