I have a page where I'm using radio buttons to determine some user options.
Option 1 will have two options within it and Option 2 is stand alone.
The HTML is as follows:
<div>
<input type="radio" name="level0" value="D" id="D" checked="checked" />
<label for="D">D</label>
<div class="sub1">
<div>
<input type="radio" name="level1" value="D0" id="D0" />
<label for="D0">D0</label>
</div>
<div>
<input type="radio" name="level1" value="D1" id="D1" checked="checked" />
<label for="D1">D1</label>
</div>
</div>
<input type="radio" name="level0" value="E" id="E" />
<label for="E">E</label>
<br>
<br>
<button id="cancel-btn" type="button">Cancel</button>
</div>
The problem revolves around the cancel button functionality.
Assuming that the radios with the 'checked' attributes are the default settings, if I start to update these but then decide to not go through with the update and hit the cancel button, I want it to revert to the default settings.
The JavaScript extract that handles this is
$('#E').click(function (event) {
$("#D0").attr('checked', false);
$('#D1').attr('checked', false);
});
$('#D0').click(function (event) {
$('#E').attr('checked', false);
$('#D').attr('checked', true);
});
$('#D1').click(function (event) {
$('#E').attr('checked', false);
$('#D').attr('checked', true);
});
$('#cancel-btn').click(function (event) {
$('input[type=radio]').prop('checked', function () {
return this.getAttribute('checked') == 'checked';
});
});
The problem is that the outer radio buttons are being reset but the inner (D0 and D1) are not.
Thoughts?
Use this in your cancel button code
$('input[type=radio]').attr('checked', false);
$('input[type=radio][default]').attr('checked', true);
This is probably what #billy meant, when he said you should add an arbitrary (in this case "default") attribute
Related
I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.
This question already has answers here:
How to check a radio button with jQuery?
(33 answers)
Closed 6 years ago.
I have this portion of code:
var checkout_options = $("#checkout").find("input[type='radio']");
$('#button-account').on('click', function () {
alert(checkout_options.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
<input type="button" value="Continue" id="button-account">
</div>
What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.
You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.
var selected = $("#checkout").find("input[type='radio']");
selected.change(function(){
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
You can make it simpler using :radio pseudo-class selector
$("#checkout :radio").change(function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b>
</label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
Your handler is only being attached to the radio button that is checked, so no handler exists for the second radio button. Attach a handler to both radio buttons:
var $radioBtn = $( "#checkout" ).find( "input[type='radio']" );
$radioBtn.on( 'change', function() {
if ( this.checked ) {
alert( this.value );
}
});
It didn't work, because you register the event handler for the initially checked value only. This is how to make it dynamically reflect the value change:
var selected = $("#checkout").find("input[name='account']");
selected.change(function(){
alert($(this).val());
});
This also makes sure that only the current radio button group is included, so you can have additional ones.
Jsfiddle:
https://jsfiddle.net/sjmhdasw/
Just use
$("input[type='radio']").on("change", function() {
console.log(this.id + " checked !");
});
It binds an event listener on all the inputs of type radio !
No need to store the selectors inside a variable (unless you're doing something with it, somewhere else in your code)
How to change submit button text based on which radio-button is active?
Here is my code, but it does not work. It changes text only once.
I have two radio-buttons:
<input type="radio" name="build-team" class="choose" value="build" /> Yes
<input type="radio" name="build-team" class="choose" value="show" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
And I have script:
$(document).on('click', '.choose', function() {
var target = $('.show-result');
if ($(this).attr('checked') == 'checked') {
target.html(target.data('chooseyes'));
}
else {
target.html(target.data('chooseno'));
}
})
JSFiddle example
$(document).on('click', '.choose', function() {
var target = $('.show-result');
target.html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="build-team" class="choose" value="Yes" /> Yes
<input type="radio" name="build-team" class="choose" value="No" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>
$('.opt').click(function(){
$('#button').html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="opt" name="opt" type="radio" value="Yes" checked="checked">Yes
<input class="opt" name="opt" type="radio" value="No">No
<button id="button" type="submit">Yes</button>
This is the easiest answer, no added attributes, only clean HTML + jQuery, it is also important to realize that there must always be a radio selected/checked by default, if not, you would have to validate the field and validating a radio is not cool haha :) have a nice day!
I try to make something like that work, implementing it in my CMS:
Fixed CMS part:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<input value="yes"></input>
<input value="no"></input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
own JS part someting like:
function EnableTextbox(radioListId,spanId)
{
if(document.getElementById(radioListId).inputValue == "yes")
document.getElementById(textBoxId).visibility = visible;
else
document.getElementById(textBoxId).visibility = hidden;
}
But I am not quite sure how to put it correctly - my understanding of js is not really high enough.
Any helping comments are highly appreciated!
try this
HTML
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" name="showhide"> Show</input>
<input type="radio" value="no" name="showhide"> Hide</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
Script
$(document).ready(function () {
$("#txtBoxId").hide();
$("input[name='showhide']").on("click", function () {
var option = $(this).attr('value');
if (option == "yes") {
$("#txtBoxId").show();
} else {
$("#txtBoxId").hide();
}
});
});
Fiddle Sample
There are a few changes you need to make:
the inputs need to have a type="radio" to indicate that those are radio buttons.
the inputs need to have a common name="whatever" to indicate that both belong to same group and cannot be checked simultaneously.
the inputs need to have a text between the opening/closing tags, this text appears next to the radio button.
you need to call the javascript function when you click/change the buttons, and inside you check which radio was selected.
you pass the radio button reference into the javascript function by writing this as the function variable.
inside the function you retrieve the radio button reference, you can name the variable whatever you want.
you are using visible and hidden as variables, but those are not defined. it supposed to be either a string, or a boolean value. i prefer to use css for that purpose.
here is an Example Fiddle
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" onclick="EnableTextbox(this);" name="Answer">Yes</input>
<input type="radio" value="no" onclick="EnableTextbox(this);" name="Answer">No</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
JS:
function EnableTextbox(radioList) {
if (radioList.value == "yes") document.getElementById("txtBoxId").style.visibility = "visible";
else document.getElementById("txtBoxId").style.visibility = "hidden";
}
Since onclick="" is outdated you should use the element.addEventListener();!
Here is an Example in Fiddle!
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<label><input type="radio" name="answer" id="yes" value="yes" />Yes</label>
<label><input type="radio" name="answer" id="no" value="no"/>No</label>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
JS:
var yes = document.getElementById('yes');
var no_ = document.getElementById('no');
if (yes.addEventListener) {
yes.addEventListener ("RadioStateChange", OnChange, false);
no_.addEventListener ("RadioStateChange", OnChange, false);
}
function OnChange(){
if (yes.checked) {
document.getElementById('txtBoxId').style.display = 'inline';
}
else {
document.getElementById('txtBoxId').style.display = 'none';
}
}
Greetings from Vienna
In jQuery
<span id="spanId">
<input type="radio" name="radiobutton" value="yes" />
<input type="radio" name="radiobutton" value="no" />
</span>
$('#spanId input:radio[name="radiobutton"]').change(function(){
if($(this).val() === 'yes'){
$('#txtBoxId').show();
} else {
$('#txtBoxId').hide();
}
});
Explanation
$('#txtBoxId').show() = display:block;
$('#txtBoxId').hide() = display:none;
If you want visibility instead.
$('#txtBoxId').css('visibility','visible');
$('#txtBoxId').css('visibility','hidden');
Let me know if you have any question.
edit: Contacted the prof; I'm not actually [supposed] to use jQuery on this assignment as the action on the form (e.g. prof's website) doesn't allow for it. Tyvm to all who replied so quickly and helpfully. Therefore, I am interested in a pure, native JS soln. to resolving these difficulties:
getting a group of checkboxes to toggle "on or off" based on whether the user clicks "Yes" or "No" radio button in a DOM-oriented form. Here's the HTML for (I: the radio buttons, II: the checkboxes):
I:) Radio Buttons
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()"></input>
<label>Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()"></input>
<label>No</label>
II.) Checkboxes
<fieldset>
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
Using the rationale provided in posts such as Populating Checkboxes Based on Radio Button Click, which still uses jQuery, the best attempt I have made thus far is:
<script>
function subscribe(){
//var yesPlease = document.getElementById("rad1");
//var noThx = document.getElementById("rad2");
var arr = new Array["cor", "sof", "lspa", "cyn", "tos", "spal"];
//var hold = document.getElementById(arr[i]);
//if(hold.getAttribute(arr[i]).checked = true && arr[i] >= 1){
//document.getElementById("cor").innerHTML=hold.getAttribute("checked");
var hold = document.getElementsByName("mailinglist")[0];
for(var i = 0; i < arr.length; i++)
{
if(document.getElementById("rad1").checked==true)
{
hold.getAttribute(arr[i]).checked == true;
}
else if(document.getElementById("rad2").checked==true)
{
hold.getAttribute(arr[i]).checked == false;
}
}
}
</script>
When I load my document and click on either, nothing happens. Here's the screenshot of the concerned section if it helps:thanks:
Remove your inline javascript code and try attaching the event in the js file itself..
Try this
$('#rad1,#rad2').on('click', function() {
$('fieldset input[type="checkbox"]')
.prop('checked',this.value === 'Yes');
}
});
Check Fiddle
You need to an action handler when the radio button is clicked. So that the element attribute "checked" is correctly updated upon clicking.
The code below is edited from yours to just include the click handler on all input type radio
$(document).ready(function(){
function subscribe() {
$('input[type="radio"]').click(function(){
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked == true){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked == true) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
});
}
subscribe();
});
JSFiddle: http://jsfiddle.net/MSZtx/
This simple code will solve the issue,
JavaScript in HEAD section :
$(document).ready(function(){
$(".radio-button").click(function(){
if($(this).val() == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
});
})
Also add, the jquery library CDN source before the above code.
Markup in BODY section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()" class="radio-button"></input><label> No</label>
<fieldset class="checkbox-list">
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
There is also a 2nd option to do the same task,
JavaScript in HEAD section :
/* Solution - 2 */
function subscribe(ele)
{
if(ele == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
}
Also add, the jquery library CDN source before the above code.
Changes in MARKUP in body section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe(this.value)" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe(this.value)" class="radio-button"></input><label> No</label>
Your Code is just working perfectly :- see here:- http://jsfiddle.net/LeWbR/2/
the only problem I could imagine
have you included jquery in your page .
where you have placed your JS function.
see the left hand side dropdown in JSfiddle, if you change the the value from no wrap(body) to
onDomReady or onLoad it won't work.
function subscribe() {
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
}