How to toggle div visibility using radio buttons? - javascript

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.

I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.

I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().

JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});

You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});

.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}

use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

Related

Given two yes/no fields, how can I use JavaScript to make the field 2 value checked "Yes" whenever the field 1 value is checked "Yes"?

If Field 1 is checked "Yes" then Field 2 should be checked "Yes"
This is what I've been trying so far:
Field 1:
<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field1||Question15||ENDFIELDTAG|| </label></div>
<div class="col9"><input type="radio" name="Field1" id="Question15yes" value="Yes" onclick="Check()">Yes <input type="radio" name="Field1" value="No" onclick="Check()">No</div>
Field 2:
<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field2||Question16||ENDFIELDTAG|| </label></div>
<div class="col9"><input type="radio" name="Field2" id="Question16yes" value="Yes" onclick="Check()">Yes <input type="radio" name="Field2" value="No" onclick="Check()">No</div>
I was trying something as simple as this js below, but I'm definitely missing something. Any help would be greatly appreciated!
<script language="JavaScript">
function Check() {
$("#Question15yes").click(function(){
if ($(this).is(':checked'))
{
$("#Question16yes").val("Yes");
}
}
});
}
</script>
Make sure you are including JQuery in your page.
To bind your event, you need to wait that the DOM is fully loaded, else you would try to use an element that doesn't exist yet.
<script language="JavaScript">
$(function() {
$(".question-checkbox").click(function(){
if ($(this).is(':checked'))
{
console.log($(this));
}
});
});
</script>
Also, you might want to change the JQuery selector from ID to class, so that you can use the same code for all similar checkboxes.
Put a .question-checkbox class on the inputs, and remove all onclicks.
You don't have to call check on every click. Once document loads, call it once.
window.addEventListener("load", function(){
$("input[type='radio']").on("click", function(){
if($("#Question15yes").is(':checked'))
$("#Question16yes").prop("checked", true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entire">
<div class="col3">
<label class="label-right">||FIELDTAG Field1||Question15||ENDFIELDTAG|| </label>
</div>
<div class="col9">
<input type="radio" name="Field1" id="Question15yes" value="Yes">
Yes
<input type="radio" name="Field1" value="No" >No
</div>
<div class="entire">
<div class="col3">
<label class="label-right">||FIELDTAG Field2||Question16||ENDFIELDTAG|| </label>
</div>
<div class="col9">
<input type="radio" name="Field2" id="Question16yes" value="Yes">
Yes
<input type="radio" name="Field2" value="No">
No
</div>
Use this for a single checkbox with the class name "example":
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});

radiobuttons and conditional checkbox

I have 2 radio-buttons and a checkbox.
When the first option is "personalized" the checkbox "hidden" should be automatically checked.
<div class="field-type-list-text field-name-field-main-download-category field-widget-options-buttons form-wrapper" id="edit-field-main-download-category"><div class="form-item form-type-radios form-item-field-main-download-category-und">
<label for="edit-field-main-download-category-und">Main Download Category </label>
<div id="edit-field-main-download-category-und" class="form-radios"><div class="form-item form-type-radio form-item-field-main-download-category-und">
<input type="radio" id="edit-field-main-download-category-und-general" name="field_main_download_category[und]" value="general" class="form-radio" /> <label class="option" for="edit-field-main-download-category-und-general">General </label>
</div>
<div class="form-item form-type-radio form-item-field-main-download-category-und">
<input type="radio" id="edit-field-main-download-category-und-personalized" name="field_main_download_category[und]" value="personalized" class="form-radio" /> <label class="option" for="edit-field-main-download-category-und-personalized">Personalized </label>
</div>
</div>
</div>
</div><div class="field-type-list-boolean field-name-field-hidden field-widget-options-onoff form-wrapper" id="edit-field-hidden"><div class="form-item form-type-checkbox form-item-field-hidden-und">
<input type="checkbox" id="edit-field-hidden-und" name="field_hidden[und]" value="1" class="form-checkbox" /> <label class="option" for="edit-field-hidden-und">Hidden </label>
</div></div>
I've made this script, but it is not working:
jQuery(document).ready(function () {
if ( $('.personalized input').val() = "personalized" ) {
$('.checkbox input').attr('checked');
}
});
You have few problems. As others already pointed out, you are checking document.ready instead of onChange event. So it checks on page load, instead of checking on radio button state change.
Another problem is that you are checking $('.personalized input') value, but you do not have personalized class in your html.
Your radio buttons have common class form-radio. So you can use it as a selector.
$('.form-radio').on("change", function(){
if ( $(this).val() == "personalized" ) {
$('.form-checkbox').prop('checked', true);
}
else{
$('.form-checkbox').prop('checked', false);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field-type-list-text field-name-field-main-download-category field-widget-options-buttons form-wrapper" id="edit-field-main-download-category"><div class="form-item form-type-radios form-item-field-main-download-category-und">
<label for="edit-field-main-download-category-und">Main Download Category </label>
<div id="edit-field-main-download-category-und" class="form-radios"><div class="form-item form-type-radio form-item-field-main-download-category-und">
<input type="radio" id="edit-field-main-download-category-und-general" name="field_main_download_category[und]" value="general" class="form-radio" /> <label class="option" for="edit-field-main-download-category-und-general">General </label>
</div>
<div class="form-item form-type-radio form-item-field-main-download-category-und">
<input type="radio" id="edit-field-main-download-category-und-personalized" name="field_main_download_category[und]" value="personalized" class="form-radio" /> <label class="option" for="edit-field-main-download-category-und-personalized">Personalized </label>
</div>
</div>
</div>
</div><div class="field-type-list-boolean field-name-field-hidden field-widget-options-onoff form-wrapper" id="edit-field-hidden"><div class="form-item form-type-checkbox form-item-field-hidden-und">
<input type="checkbox" id="edit-field-hidden-und" name="field_hidden[und]" value="1" class="form-checkbox" /> <label class="option" for="edit-field-hidden-und">Hidden </label>
</div></div>
This part:
else{
$('.form-checkbox').prop('checked', false);
}
you only need if you want to un-check if not personalized.
Also take care of .prop() which is used for jQuery 1.6+. For lower versions use .attr()
You have to specify when do you want the script to check if the radio is checked or not. If you use just document.ready() function, it will check it only once, when the site is loaded and since it's not checked - the checkbox won't be checked neither.
You can use following approach: check it with every click event on the radio button.
$('.personalized').click(function() {
if ($(this).is(':checked')) {
$('.checkbox').attr('checked', 'checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='radio' class='personalized'>
<input type='checkbox' class='checkbox'>
Simply you need to do it in ready function
jQuery(document).ready(function () {
if ($(".personalized").is(":checked") ) {
$('.checkbox').attr('checked', 'checked');
}
});
if you want them to apply on page load.
You have several problems here:
The code as written only runs on page load. Since you said you want the checkbox to be "automatically" checked, you should attach a change handler to the radio array.
.val() called on a radio array returns the value of the first element in the selected set, regardless of which one is checked. You need to add :checked to your selector to filter down to the one selected radio element.
Your single equals sign is the assignment operator and should be replaced with ===.
.attr('checked') returns the value of the checked attribute. There are actually two problems here: attr only looks at the attribute initially assigned to the element; you need to use prop instead to update the checked property. The second problem is that the one-parameter attr function is used to read the attribute. You want the two-parameter function to set it.
Here's a working example:
jQuery(document).ready(function () {
$('input[name="radio"]').on('change',function(){
if ( $('input[name="radio"]:checked').val() === "personalized" ) {
$('#hidden').prop('checked','checked');
} else {
$('#hidden').prop('checked','');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radio" id="personalized" value="personalized"/><label for="personalized">personalized</label><br/>
<input type="radio" name="radio" id="general" value="general"/><label for="general">general</label><br/>
<input type="checkbox" id="hidden" name="hidden"/><label for="hidden">hidden</label>

add highlight class to the label of a checked check box via a button

I have checked all over stack overflow, but they're not exactly what I need.
I have checkboxes with associated labels
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>
There is also a button, when the button is clicked, if the checkbox is checked, the label associated with it has a highlight class added to the label. I already have the highlight class written I am just having trouble applying it using the addClass method.
I have:
$(':checkbox:checked').addClass('highlight');
but it does nothing
Let's say this is your HTML:
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
and this is your CSS class:
.highlight {
background-color: yellow;
}
One thing you could do is loop through each checked checkbox and just apply the class using the label[for=*] property:
$('#btnSubmit').click(function() {
$('input:checked').each(function () {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
});
});
However, using the above method, you're not allowing a way to remove the highlight class should you uncheck a box and hit Submit again. I would prefer the below method... which loops through ALL checkboxes, and tests them to determine if they're checked or not:
$('#btnSubmit').click(function() {
$('input[type=checkbox]').each(function () {
if (this.checked) {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
} else {
$("label[for='" + $(this).attr('id') + "']").removeClass("highlight");
}
});
});
Try this Fiddle
I'm trying to find a way to just reference the label of all checked checkboxes in one line of code. Because if you could do that, you can just do away with the looping and the if statements. I'll keep researching, and if I find it, I'll edit my post accordingly.
Update: Okay, I think I understand what you need. See updated example.
The trick is knowing how to find the label and checkbox associated with the button. Since the buttons were not included in the question code, I had to guess. If the button is elsewhere, you can experiment using these jQuery traversing methods.
$(document).ready(function(){
$('#mybutt').click(function(){
var chkboxes = $('input[type=checkbox]');
$(chkboxes).each(function(){
if ( $(this).is(':checked') ){
$(this).parent().find('label').addClass('highlight');
}else{
$(this).parent().find('label').removeClass('highlight');
}
});
});
}); //END document.ready
.highlight{background:red;color:yellow;padding:2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label>
<p>
<button id="mybutt">Go</button>
I guess, what you are trying to do is to change a class, after the value of your checkbox has changed, easiest way to do this is using the onChange event, you can also bind the event with jQuery using $('#your_checkbox').on('change', function(){})
$('[type="checkbox"]').on('change', function() {
if (!$(this).attr('checked')) {
$(this).attr('checked', 'checked');
$(this).parent().addClass('checked');
} else if ($(this).attr('checked') === 'checked') {
$(this).removeAttr('checked', '');
$(this).parent().removeClass('checked');
}
});
$('#btnSubmit').on('click', function() {
var inputs = $(this).parent().parent().find('[type="checkbox"]')
inputs.each(function(){
if ($(this).attr('checked') === 'checked') {
$(this).parent().addClass('iam-checked');
}
else {
$(this).parent().removeClass('iam-checked');
}
});
});
.checked {
border-bottom: 1px solid green;
}
.iam-checked {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
This is a little late, but I was surprised that no one mentioned the next method. You are trying to style the label after the checkbox, not the checkbox itself. In other words, the label is the next sibling of the checkbox.
I think this is the most jQuery way to solve this so wanted to add my two cents.
$("#bt").on("click", function() {
$(":checked").each(function() {
$(this).next().addClass("highlight");
});
});
.highlight { background: gold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>

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);
});

Using .parent to select divs

I have a script which greys out a text area whenever the yes radio button is selected. I would like to modify the jquery script so that the textarea can be in a different div and still be disabled as before.
Looking through the jquery docs it looks to me I can do this using .parent but I'm having trouble getting it to work.
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
How can I do this? Or is there a better way?
Edit:
$(function () {
var $choices = $(".group").find(":radio");
$choices.on("change", function () {
var $this = $(this);
var tarea = $this.closest(".group").next(".group").find("textarea");
if ($this.val() === "yes") {
tarea.val('');
tarea.prop('readonly', true);
tarea.css('background-color', '#EBEBE4');
} else {
tarea.prop('readonly', false);
tarea.css('background-color', '#FFFFFF');
}
});
});
Added to each <textarea> the attribute "trigger". Determinates it's trigger element by name. For example <textarea data-trigger="choice2"> means <input name="choice2"/> change's it's stare (gray/or not).
This way you can add your textarea elements anywhere inside your page without worries.
Here is an example: http://jsfiddle.net/r0gw8t1b/2/
var tarea = $this.closest(".group").next(".group").find("textarea");
You can use next() to achieve that. It finds the parent group and then looks at immediate sibling and looks for textarea.
<div class="group">
<input type="radio" name="choice1" value="yes" />Yes
<input type="radio" name="choice1" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
DEMO
This jsFiddle shows how it could be done.
$($(this).parent().siblings('div.group')[0]).find('textarea');
Find the text area inside the parents siblings of type div.group, and then you can set the css or whichever attributes you want to set as seen in the jsFiddle.
The below code works well for the selection and disabling the desired text area:
HTML:
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
JQUERY:
$(function () {
$( "input[type='radio']" ).click(function () {
if ($(this).val()=='yes') {
$('.group textarea').attr('readonly',true);
$('.group textarea').css('background-color', '#f1f1f1');
} else {
$('.group textarea').attr('readonly',false);
$('.group textarea').css('background-color', '#fff');
}
});
});

Categories

Resources