Show one div and hide the other by checked radio button - javascript

I'm trying to learn how to use jquery to show/hide elements dependent on values. i'm not sure if .show / .hide is the right choice so any help will be appreciated...
Here is my example on jsfiddle where I have 2 radio buttons and 2 divs.
I want Jquery to show a single div by the dependency of the checked radio button, so it will show only the one that is checked.
HTML:
<input type="radio" name="one" value="01" checked> Male<br>
<input type="radio" name="two" value="02"> Female<br>
<div class="showhide">
show me when 01 is checked.
</div>
<div class="showhide">
show me when 02 is checked.
</div>
JQuery (trying to understand what to do here):
$("div.showhide").hide();
$("div.showhide").show();
// or maybe with:
$("div.showthis").toggle(this.checked);

Using data-* attributes comes in handy in such practices. Rember that the radios name attributes must be the same that one and only one checkbox can be checked at any given time. And, there is no p tag in your code, at least in the example provided, so why bother prefixing the selector with it?
The following example makes use of data-section attribute which has the selector for the element that must be shown when the checkbox is checked. It is worth mentioning that this is code is dynamic and does not require changing the code when adding more inputs with divs.
$(function() {
// listen for changes
$('input[type="radio"]').on('change', function(){
// get checked one
var $target = $('input[type="radio"]:checked');
// hide all divs with .showhide class
$(".showhide").hide();
// show div that corresponds to selected radio.
$( $target.attr('data-section') ).show();
// trigger the change on page load
}).trigger('change');
});
.showhide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" name="one" data-section="#div-1" value="01" checked>Male<br>
<input type="radio" name="one" data-section="#div-2" value="02">Female<br>
<div id="div-1" class="showhide">
show me when 01 is checked.
</div>
<div id="div-2" class="showhide">
show me when 02 is checked.
</div>

Related

When you write a program to toggle all checkboxes, is there a way to not include other checkboxes outside of that group?

I understand how to toggle the status of all check-boxes to checked or not-checked by a single click, either by a check-box or a link. That is the easy part.
But I also have several check-boxes that I do not want to toggle on or off by a single click, that are not part of the group that should be affected. These check-boxes need to be protected.
Below is an example. I can click the bottom checkbox to toggle, but it should only affect Item 1 through Item 3 check-boxes. When I click the bottom checkbox, it should not toggle the first two check-boxes that should be protected.
Thanks...
$(function() {
$('#toggle-all').click(function(event) {
var selected = this.checked;
$(':checkbox').each(function() {
this.checked = selected;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- These next two checkboxes should not be part of the checkboxes to be all toggled on or off -->
<input type='checkbox' name='notAssociated1'>This checkbox should be protected from ability to toggle all below<br>
<input type='checkbox' name='notAssociated2'>This checkbox should also be protected from ability to toggle all below<br><br>
<!-- The checkboxes below should be affected by clicking on the checkbox to toggle all on or off -->
<input type="checkbox" name="CB1" id="CB1" />Item 1<br>
<input type="checkbox" name="CB2" id="CB2" />Item 2<br>
<input type="checkbox" name="CB3" id="CB3" />Item 3<br>
<!-- select all boxes -->
<br><input type="checkbox" name="toggle-all" id="toggle-all" />Toggle Item 1 thru Item 3 but not the top two checkboxes
With a slight modification to your code, you can enable selecting only the checkbox inputs you want. There are multiple ways to achieve this, but I chose to surround the targeted check boxes with a fieldset element (you can use a div element or other block-level element if you wish) and use .siblings() to select only these check boxes. See the following code snippet as an example.
$(function() {
$('#toggle-all').click(function(event) {
var selected = this.checked;
$(this).siblings(":checkbox").each(function() {
this.checked = selected;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- These next two checkboxes should not be part of the checkboxes to be all toggled on or off -->
<fieldset>
<input type='checkbox' name='notAssociated1'>This checkbox should be protected from ability to toggle all below<br>
<input type='checkbox' name='notAssociated2'>This checkbox should also be protected from ability to toggle all below<br><br>
</fieldset>
<!-- The checkboxes below should be affected by clicking on the checkbox to toggle all on or off -->
<fieldset>
<input type="checkbox" name="CB1" id="CB1" />Item 1<br>
<input type="checkbox" name="CB2" id="CB2" />Item 2<br>
<input type="checkbox" name="CB3" id="CB3" />Item 3<br>
<!-- select all boxes -->
<br><input type="checkbox" name="toggle-all" id="toggle-all" />Toggle Item 1 thru Item 3 but not the top two checkboxes
</fieldset>
If you would prefer to keep the original layout, you can use other selectors to target the selectors you want. In your case, you can select with $("[id^=CB]") or setting classes to each of the check box elements and selecting with $(".selectAllCB") or whatever class name you would like.
if you're using jQuery selectors you can just give checkboxes groupings through id, or class.
eg. using:
$('.class-group')...
(bit of a noob myself mind!)

Targeting the nth element of certain class when nth checkbox is checked?

So I have a dynamically listed set of elements, each structured as follows:
<div class="under-item-description">
<span class="under-compare-price">100</span><span class="under-price">50</span>
<span class="under-compare-price-2">200</span><span class="under-price-2">100</span>
<div class="under-quantity">
<label class="under-quantity-button">
<input type="radio" checked="checked" name="quantity-1" class="under-quantity-radio" value="1"/>
</label>
<label class="under-quantity-button">
<input type="radio" name="quantity-2" class="under-quantity-radio" value="2"/>
</label>
</div>
</div>
The amount of times the .under-item-description div is shown on the page can change. Currently, it shows four times.
What I am trying to do is when a user clicks on the first checkbox (name="quantity-1") in any given .under-item-description div, that div's .under-compare-price and .under-price shows, while .under-compare-price-2 and .under-price-2 are hidden.
If the second checkbox (name="quantity-2") is clicked, then .under-compare-price-2 and .under-price-2 are shown while .under-compare-price and .under-price are hidden, only in that .under-item-description div.
Here's my JS:
$('.under-quantity-button').click(function(){
$('.under-quantity-radio').each(function(){
if($(this).is(':checked')){
$('.under-compare-price:eq('+$(this).parents('.under-item-description').index()+'), .under-price:eq('+$(this).parents('.under-item-description').index()+')').show();
$('.under-compare-price-2:eq('+$(this).parents('.under-item-description').index()+'), .under-price-2:eq('+$(this).parents('.under-item-description').index()+')').show();
}
});
});
However, it doesn't seem to function as I want. Regardless of which second checkbox is clicked, I have the prices appear on the 1st and 3rd elements. And it doesn't switch back when the first checkbox is clicked anywhere. Any help?
Surround each selection of radio buttons in a
<fieldset></fieldset>
This will allow them to work independently, then use jQuery closest() to select the elements to hide.
https://api.jquery.com/closest/

Can't Check Checkbox in jQuery Collapsable Element

I'm using the following code to allow for an accordion effect on a series of table rows.
$('.accordian-body').on('show.bs.collapse', function () {
$(this).closest("table")
.find(".collapse.in")
.not(this)
.collapse('toggle')
});
Inside the collapsed rows I also have a series of checkboxes, to allow for options to be selected:
<div style="float:right;margin-top:-5px;" class="checkbox check-primary checkbox-circle">
<input id="checkbox1" type="checkbox" checked="checked" value="1">
<label for="checkbox1"></label>
</div>
These checkboxes cannot be checked or unchecked, even if not disabled, although the mouse pointer will chance to indicate a clickable element is there.
How can I re-enable the checkboxes?
Thanks!

Unchecking a radio box without use of id's

I'm setting up a table, where each row will contain several radio boxes. There are certain conditions for the radio boxes, for example:
If "Home" is checked, the "Text" radio box will be unchecked and "Voice" will be checked instead (ie. You can't text a home phone number). Similarly, when "Home" and "Voice" are checked, clicking "Text" will force "Home" to be unchecked and "Cell" will become checked.
I can get this working fine for one instance, with the use of .getElementById and the click function, but where I run into trouble is when things are scaled up. This table might have 20 or 30 rows, each of which containing a cell with these radio boxes.
I'm not great with jQuery, so I'm not sure how to make a more general version, so that each set of radio boxes are their own contained units, so to speak. I made a jsfiddle where you can see that only the first instance is working, likely because I am targeting the boxes using their id and you can't have two elements with the same id... help? Thanks!
http://jsfiddle.net/3uHqS/
Script
$( document ).ready(function() {
document.getElementById('contact-home').onclick = function () {
document.getElementById('format-voice').checked = true;
};
document.getElementById('format-text').onclick = function () {
document.getElementById('contact-cell').checked = true;
};
});
HTML
<form>
<input type="radio" name="contact" value="" id="contact-cell" />
<label for="contact-cell">Cell</label>
<input type="radio" name="contact" value="" id="contact-home" />
<label for="contact-home">Home</label>
<input type="radio" name="format" value="" id="format-voice" />
<label for="format-voice">Voice</label>
<input type="radio" name="format" value="" id="format-text" />
<label for="format-text">Text</label>
</form>
You are going to want to assign every radio box a descriptive class like 'text-radio' or 'home-radio'. Then when you need to change all of the Text radio boxes you do something like the following in jQuery:
$(".text-radio").attr('checked', 'checked');

jQuery/JavaScript - Hide / Show Drop down box pending on Radio Button

I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>​
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});​
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});

Categories