Show / Hide contents base on radio button selection - javascript

I am trying to toggle a content DIV base on the selection of radio buttons.
HTML for radio button.
<div class="row-fluid">
<label class="radio">
<input type="radio" name="account" id="yes" value="yes" checked>
Yes, I have an existing account
</label>
<label class="radio">
<input type="radio" name="account" id="no" value="no">
No, I don't have an account
</label>
</div>
Content DIV
<div id="account_contents">
<p>This is account contents.......</p>
</div>
This is how I tried it in jquery.
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
But it doesn't work for me correctly. Here I want to show this content DIV only if user don't have an account.
Can anybody tell me how to fix this problem?

seems you need .on('change') for radio buttons not just for one of them
$('input[type="radio"][name="account"]').on('change',function(){
var ThisIt = $(this);
if(ThisIt.val() == "yes"){
// when user select yes
$('#account_contents').fadeOut();
}else{
// when user select no
$('#account_contents').fadeIn();
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
}
});
Working Example

$(document).ready(function(){
$('.radio input[type="radio"]').on("click", function(){
if($('.radio input[type="radio"]:checked').val() === "yes"){
$("#account_contents").slideDown("slow");
}else{
$("#account_contents").slideUp("slow");
}
});
});

I'm not sure if I got you right, but this fiddle toggles #account_contents depending on which button you click:
This was how i tweaked the script:
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
$("#yes").bind("change", function() {
$('#account_contents').fadeOut();
});

Related

How to get the selected radio button label text using jQuery

I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.
Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO
You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>
I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/

Need a way to integrate an Invert function(Check All/Uncheck All) through radio buttons - for the Checkbox group

Am relatively new to what I am doing here. I am just putting together stuff with what I find here and other open resources.
The problem I am having is - With the current setup a person can choose a radio button and check a couple boxes and goto the other radio button option and choose boxes under that. I am trying to get the Checkboxes to be All Checked when someone selects the radion option and UncheckALL when the person chooses another option on the radio button group.
So if I select option 'a' under 'GENERAL' and then goto 'DETAILED' - 'a' should be unchecked.
Heres the code I am using in JFiddle
HTML:
<div id="RadioWidget">
<label><input type="radio" name="chkboxs" value="General" />General Clean</label>
<label><input type="radio" name="chkboxs" value="Detailed" />Detailed Clean</label>
<label><input type="radio" name="chkboxs" value="Commercial" />Commercial Clean</label>
</div>
<div id="General" class="desc">
<p class="maintextBlue">General
<label><input type="checkbox" name="GeneralOptn[]" value="a" />a</label>
<label><input type="checkbox" name="GeneralOptn[]" value="b" />b</label>
</p>
</div>
<div id="Detailed" class="desc">
<p class="maintextBlue">Detailed
<label><input type="checkbox" name="DetailedOptn[]" value="a" />a</label>
<label><input type="checkbox" name="DetailedOptn[]" value="b" />b</label>
</p>
</div>
<div id="Commercial" class="desc">
<p class="maintextBlue">Commercial
<label><input type="checkbox" name="CommercialOptn[]" value="a" />a</label>
<label><input type="checkbox" name="CommercialOptn[]" value="b" />b</label>
</p>
</div>
Jscript:
$(document).ready(function() {
$("div.desc").hide();
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#" + test).show();
});
});
This was a piece of script I found that inverts the checkbox state. But not sure how to integrate it to the radio button. this snippet was working off a onClick() fn for a button.
$("A[href='#invert_selection']").click( function() {
$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each( function() {
$(this).attr('checked', !$(this).attr('checked'));
});
return false;
});
Any help is much appreciated...
this requires you to add IDS to your input fields... but it would work.
If you want to control multiple input fields you can always uses classes to..
jQuery("#generalA").click(function(){
if(jQuery(this).is(':checked')){
// is checked do some stuff if you want
}else{
// is mot checked uncheck the checkbox with an ID of #detailedA
jQuery('#detailedA').prop('checked', false);
}
return false;
});
The above response by AndrewMac helped.
I just had to figure out a way it helped my existing setup.
Below is the small addition I did to get the desired setup - this way it actually disables all the unnecessary inputs thereby eliminated from the final send out of the form.
$(document).ready(function() {
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("#" + test).show().find('input, textarea').prop('disabled', false);;
});
});
I have also updated the same on my fiddle page. Fiddle
Thanks for the help AndrewMac - Sorry for the long time to post this response/answer.

Show Field if Radio Button is Selected

I'm attempting to get the Website URL field on this page to display only when the previous question has the radio button "Yes" selected. I've searched and tried a few code examples, but they aren't working. Does anyone have any suggestions for me?
Thanks in advance!
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div>
</div>
</div>
<div class="editfield">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>
I noticed that you initally put the javascript I gave you at the top of the page. If you are going to do this then you need to encapsulate the code in a jquery $(document).ready(function(){ });. You only need to use a document ready when your html follows after the javascript.
$(function() {
// place code here
});
However, in this scenario I have created another alternative that will be better, but do not forget that you have to initially set the web url div as hidden. Also, I highly recommend that you set better control ids; it will make your javascript easier to understand.
$('input[name=field_8]').on("click", function(){
var $div_WebUrl = $('#field_19').closest('.editfield');
if($('input[name=field_8]').index(this) == 0)
$div_WebUrl.show();
else
$div_WebUrl.hide();
});​
Live DEMO
I have created a little example:
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div>
</div>
</div>
<div class="editfield" id="divUrl" style="display:none">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>​
jsFiddle: http://jsfiddle.net/EQkzE/
Note: I have updated the div to include a style, cause I do not know what your css class looks like. Good luck.
Here's a pure JS Solution:
document.getElementById("field_19").parentNode.style.display = "none";
document.getElementById("option_9").onclick = toggleURLInput;
document.getElementById("option_10").onclick = toggleURLInput;
function toggleURLInput(){
document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none";
}
Not a very dynamic solution, but it works.
Something like this will bind the click event to a simple function to look at the radio button and show the other div.
$('#option_9').on('click', function() {
if ($('#option_9').is(':checked')) {
$('#field_19').closest('.editfield').show();
} else {
$('#field_19').closest('.editfield').hide();
}
});
Run sample code

Disappearing radio button and clickable labels

I want to make radio buttons disappear and instead of buttons, the label of the radio buttons will be clickable itself and i will change the background color of the selected radio. How can i do this? For example, I have "yes" and "no" labels and these labels will be clickable and there will be no radio buttons at all. These are only changing color of background but showing radio buttons which is not wanted.
Javascript
$(document).ready(function(){
var ok = "green";
var notok = "red";
$.each($(":radio"), function(){
if($(this).prop("checked") == false)
{
$(this).parent().css("background", notok);
}
else
{
$(this).parent().css("background", ok );
}
})
$(":radio").click(function(){
$("[name='"+$(this).prop("name")+"']").parent().css("background", notok);
$(this).parent().css("background", ok );
})
})
HTML
<FORM name="form1">
<div>
<input type="radio" id="yes" name="q"checked="checked"/> Yes
</div>
<div>
<input type="radio" id="no" name="q"/>No
</div>
</FORM>
Thanks
This one is actually deceptively easy. If you just use a "label" tag, it will be clickable. Then you can simply hide the radio button.
<input id="yes" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="yes">Yes </label>
<input id="no" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="no">No</label>
btw, here's a JSFiddle of it working: http://jsfiddle.net/scGE9/2/
If I understand what you're asking, I'd hide the radio buttons, then attach a click handler to the labels that changed the background color:
$('label').click(function () {
$('label').removeClass('selected');
$(this).addClass('selected');
});
Here's a jsfiddle to demonstrate.
In short, when a label is clicked, remove the 'selected' class controlling the background color from all relevant labels, and apply it to the one that was clicked.

JavaScript: Set background of radio button when deselected (group of radio buttons)

I am trying to create a simple interactive form for use with touch screen devices. The majority of the form is made up of radio buttons in groups of 5 (approx. 37 groups). I have a label tag for each radio button, and when selected (clicked), the background-color property of the label is changed to a highlighted colour using this JavaScript within each label tag OnClick="this.style.background='#5555ff';"
What I want to add to the above, is a JavaScript that will remove the above if the selection is changed within the group. E.g. A user selected radio button A in group 1, then changes their selection to radio button B in group 1. At the moment, both label backgrounds will be changed to the defined colour.
The HTML form is created dynamically by PHP so radio button names, IDs, & values will differ.
I have been unsuccessful trying to complete this task myself, and there doesn't seem to be a simple OnUnClick="xxx" either. I have searched on here for a solution but no questions match mine, although I have tried tweaking existing solutions to similar problems but to no avail.
Thank you for reading!
Here you go:
HTML
<html>
<body>
<div>
<input type="radio" id="g1v1" name="g1" value="v1" checked="checked"/> <label for="g1v1">V1</label>
</div>
<div>
<input type="radio" id="g1v2" name="g1" value="v2" /> <label for="g1v2">V2</label>
</div>
<div>
<input type="radio" id="g1v3" name="g1" value="v3" /> <label for="g1v3">V3</label>
</div>
<div>
<input type="radio" id="g1v4" name="g1" value="v4" /> <label for="g1v4">V4</label>
</div>
</body>
</html>
Javascript
$(document).ready(function(){
var selectedRadioColor = "yellow";
var normalRadioColor = "gray";
// For changing color while document loads
$.each($(":radio"), function(){
//alert( $(this).prop("id")+ $(this).prop("checked") );
if($(this).prop("checked") == false)
{
$(this).parent().css("color", normalRadioColor);
}
else
{
$(this).parent().css("color", selectedRadioColor );
}
})
// For updating color when user interacts with radio buttons
$(":radio").click(function(){
$("[name='"+$(this).prop("name")+"']").parent().css("color", normalRadioColor);
$(this).parent().css("color", selectedRadioColor );
})
})
Here is the link to jsfiddle for live demo:
http://jsfiddle.net/dharmavir/6UnDs/
assuming your radio buttons are grouped in a divs like this -
<div class="radio-group">
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR>
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR>
<INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P>
</div>
You can do something like this in jquery -
$('input[type="radio"]').click(function(){
var parentElement = $(this).parent();
parentElement.find('input').css('background', '#000000'); //set to your neutral background for radio buttons
$(this).css('background', '5555ff');
});

Categories