I can toggle the show/hide of a checkbox because it can be unchecked but the behavior is different on a radio group because clicking a checked radio button doesn’t uncheck it, only clicking another radio button in the same group.
DEMO WORKS FOR CHECKBOX NOT RADIO GROUPS
How can I modify this so it works for radio buttons and checkboxes in the same function? In this example I can click Item4 but it doesn’t hide upon clicking the others in the radio group.
How it should work:
Put data-info-id="infox" on the input
Put id="infox" on the container usually a div
jQuery solutions are welcome.
HTML
<input type="checkbox" id="item1" data-info-id="info1" />
<label for="item1">Item 1 Checkbox</label>
<br/>
<div id="info1">Content checkbox group</div>
</p>
<input type="radio" id="jb1" name="jb" />
<label for="jb1">Item2 Radio</label>
<br/>
<input type="radio" id="jb2" name="jb" />
<label for="jb2">Item3 Radio</label>
<br/>
<input type="radio" id="jb3" name="jb" data-info-id="info2" />
<label for="jb3">Item4 Radio</label>
<br/>
<div id="info2">Content radio group</div>
CSS
[id^="info"] {
display: none;
}
JS
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div)
div.style.display = checked ? 'block' : 'none';
}
});
I first added two containing divs around the checkbox and the radio buttons:
<div id="checkbox">
<input type="checkbox" id="item1" data-info-id="info1" />
<label for="item1">Item 1 Checkbox</label>
</div>
<br/>
<div id="info1">Content checkbox group</div>
</p>
<div id="radios">
<input type="radio" id="jb1" name="jb" />
<label for="jb1">Item2 Radio</label>
<br/>
<input type="radio" id="jb2" name="jb" />
<label for="jb2">Item3 Radio</label>
<br/>
<input type="radio" id="jb3" name="jb" data-info-id="info2" />
<label for="jb3">Item4 Radio</label>
<br/>
</div>
<div id="info2">Content radio group</div>
I then added a for loop to loop through the children of the parent of the item clicked. Because it was only triggering the change event for the clicked item.
document.addEventListener('change', function (e) {
var children = e.target.parentNode.children;
for(var i = 0; i < children.length ; i ++)
{
var id = children[i].getAttribute('data-info-id');
var checked = children[i].checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
}
});
This works for me. It's a little down and dirty but it works just fine.
For the radio buttons. This can be done in 2 ways :
Here's the jsFiddle : http://jsfiddle.net/zvzL8u1n/
Method1
Have 2 radio buttons Show and Hide.
$("input[name=jbM1]").change(function(){
$("#" + $(this).data("info-id")).toggle();
});
jbM1 is the name for both the radio buttons.
So basically data-info-id is given in both the radio buttons and on their change the div is toggled.
Method2
Have only one radio button and make it work like checkbox
$("#jb3").click(function(){
var prev = $(this).data('prev');
if(prev == true){
$(this).prop('checked', false);
}
$(this).data('prev', $(this).prop('checked'));
$("#" + $(this).data("info-id")).toggle();
});
jb3 is id of the radio button and data-prev is used for storing prev value.
Related
I have these radio buttons:
<input name="selector" value="1" type="radio" id="1" />
<input name="selector" value="2" type="radio" id="2" />
Then, I want to show the proper dynamic <div> depending on the selected radio button.
Here's the <div> tag:
<div id="product_{selector#ID}">
...
</div>
So as you can see the ID of this <div> should be dynamic. Could it be handled with javascript?
If the div's id is dynamic, apply the same principle for :radio too:
<input name="selector" value="1" type="radio" id="r_{selector#ID}" />
<input name="selector" value="2" type="radio" id="r_{selector#ID}" />
And for the jQuery:
$(function () {
$("input:radio[name='selector']").click(function () {
$("#" + this.id.replace("r", "product")).show();
});
});
You can use this logic to do the rest.
Here is a quick and dirty way to achieve what you're after
$("input:radio[name='selector']").click(function() {
var rdId = $(this).val();
$("div").hide();
$("#product_" + rdId).show();
});
div { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="selector" value="1" type="radio" name="radio" id="1" /> 1
<input name="selector" value="2" type="radio" name="radio" id="2" /> 2
<div id="product_1">
..... 1
</div>
<div id="product_2">
..... 2
</div>
The snippet doesn't want to work on stackoverflow, but here it is in codepen
This solution manipulates the DOM of your page.
Your html would be
<body>
<input name="selector" value="1" type="radio" id="1" />
<input name="selector" value="2" type="radio" id="2" />
<div id="main">
<div id="product_{selector#ID}"></div>
</div>
Your JS
function createDiv(id) {
var myDiv = document.createElement('div');
myDiv.setAttribute('id', 'product_' + id);
document.getElementById('main').appendChild(myDiv);
}
function removeDiv() {
var element = document.getElementById("main");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
var radio1 = document.getElementById('1');
var radio2 = document.getElementById('2');
radio1.onclick = function(e) {
removeDiv();
createDiv(this.id)
};
radio2.onclick = function(e) {
removeDiv();
createDiv(this.id)
};
Now you can see in the element inspector like the DOM is modified if you select different options.
I took a bit of a different approach by creating a quick JsFiddle to demonstrate how you would dynamically handle these events using JavaScript. Here are the pieces of my example that matter:
JavaScript
//Initialize variables;
var elements, current, last;
//Initially creates the event listeners
elements = document.getElementsByClassName('product_selection');
for (var i = 0; i < elements.length; i++)
elements[i].onclick = selectProduct;
//Sets the correct div to be displayed
function selectProduct() {
current = String(this.id);
var el = document.getElementById("product_" + current);
el.style.display = "block";
if (last !== undefined)
document.getElementById("product_" + last).style.display = "none";
last = String(this.id);
}
onload
Based on whatever is currently already on the page, we set the event listeners to the radio buttons whenever they are clicked. We then append that element id to a list of ids so that we can go back to it later.
selectProduct()
Set the clicked radio button to the current item, then we want to ensure that it is displayed. After we are complete, assuming this is not the very first radio button clicked, we will hide the previously shown div and update the last item to be whatever radio button was currently clicked.
The rest of my example just allows for you to view what would happen when a dynamically created radio button/div are made and how the program would handle that DOM manipulation.
http://jsfiddle.net/ejk4z03k/5/
I cannot find a perfect solution for this.
Is there a simple way to fadeIn the ".filter_on" div, if I click on a select option and/or radio button?
And by default, get this div to fade out again afterwards?
My fiddle
<div class="filter">
Filter <span class="filter_on">active</span>
</div>
<form>
<p>Vehicle?</p>
<select name="vehicle" size="2">
<option>Bike</option>
<option>Car</option>
</select>
</form>
<form>
<p>City?</p>
<input type="radio" id="all" name="city" value="All" checked>
<label for="all"> All</label></input>
<input type="radio" id="ny" name="city" value="New York">
<label for="ny"> New York</label></input>
<input type="radio" id="mh" name="city" value="Manhattan">
<label for="mh"> Manhattan</label></input>
</form>
You don't need to fadeOut since you cannot unselect from drop-down or cannot uncheck the radio button.
$('select, :radio').on('change', function() {
if ($('select option:selected').length === 0 && $(':radio:checked').val() === 'All') {
$('.filter_on').fadeOut();
} else {
$('.filter_on').fadeIn();
}
}).trigger('change');
trigger will execute this function automatically. Will fadeIn on the page load.
Demo: https://jsfiddle.net/tusharj/vyd7a2s8/1/
Demo -> http://jsfiddle.net/vyd7a2s8/4/
var defaultRadio = $(':radio:checked');
var defaultVehicle = $('[name=vehicle] option:selected');
$('[name=vehicle],[name=city]').on('change', function (e) {
var currentRadio = $(':radio:checked');
var currentVehicle = $('[name=vehicle] option:selected');
if (currentRadio[0].isEqualNode(defaultRadio[0]) && currentVehicle[0].isEqualNode(defaultVehicle[0])) {
$('.filter_on').fadeOut(500);
} else {
$('.filter_on').fadeIn(500);
}
});
Explanation - This will store the default selected values outside the function and uses them inside the click event to check the newly selected values.
I want to validate my button when summit if not check the radio button it will show error but if we check, it will get the id of the button that we check. I try code as below:
Html:
<div class="radio">
<label>
<input type="radio" name="chk" id="chk1" class="chk"/>abcd
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chk" id="chk2" class="chk" />
efg
</label>
</div>
<input type="button" value="Visualiser le résultat..." id="btnresult" class="btn"/>
Jquery:
$('#btnresult').on('click',function(){
if ( ! $('input.chk').is(':checked') ){
alert('not check.');
}
else if($('input.chk').is(':checked')) {
var getid = $(this).parent().find(".chk").attr('checked', true).attr('id');
alert(getid);
}
});
My problem is that: I can get only the first id of radio buttonchk1 when I check on other radio button.
To get the id of the checked radio button
var getid = $('input.chk:checked').attr('id');
$(this).parent().find(".chk").attr('checked', true).attr('id') will return the id of the first element with class .chk inside the parent element which will always be the first radio element - not the checked one
If you want to be more specific in your search then use
var getid = $(this).parent().find(".chk:checked").attr('id');
$("#btnresult").click(function() {
if(!$("input.chk:checked").length) alert("Not checked");
else alert($("input.chk:checked").attr("id"));
});
Images //hide and show images with buttons
images are shown based on radio button/checkbox selected
<img id="storage_drawer" src="images/placeholder/get_hardware/storage_drawer.png" />
<img id="cash_drawer" src="images/placeholder/get_hardware/cash_drawer.png" />
Form two sets of radio buttons// changed into checkboxes by javascript function
<input type="checkbox" id="cashdrawer" name="type" value="cashDrawer" class="unique" >
<input type="checkbox" id="cashStorage" name="type" value="storageDrawer" class="unique">
//second set of radio buttons
<input type="checkbox" id="single" name="type2" value="singleLine" class="unique" >
<input type="checkbox" id="multi" name="type2" value="multiLine" class="unique" >
</form>
Start of script
$(document).ready(function(){
to make make checkboxes have the functionality of radio buttons
var $inputs = $(".unique");
$inputs.change(function(){
$inputs.not(this).prop('checked');
});
return false;
radio buttons -- first set of radio buttons
$("input[name$=type]").click(function(){
var value = $(this).val();
//Cash Drawers
if(value == 'cashDrawer') {
$("#cash_drawer").show();
$("#storage_drawer").hide();
}
else if( value == 'storageDrawer') {
$("#storage_drawer").show();
$("#cash_drawer").hide();
}
})
$("#cash_drawer").hide();
$("#storage_drawer").hide();
second set of radio buttons
$("input[name$=type2]").click(function(){
var value = $(this).val();
//Barcode Scanners
if(value = 'singleLine') {
$("#sinlgeBarcode").show();
$("#multiBarcode").hide();
}
else if(value == 'multiLine') {
$("#multiBarcode").show();
$("#sinlgeBarcode").hide();
}
})
$("#sinlgeBarcode").hide();
$("#multiBarcode").hide();
});
});
end of script
If your radio boxes have the same name attribute they will behave as radio buttons i.e only one selection can be active in the group, but if each button have their own name they can all be selected.
So if u have a collection of radios like this:
<form>
<input type="radio" name="1">
<input type="radio" name="2">
<input type="radio" name="3">
</form>
U can get them to behave like check boxes with a lil javascript:
// This will allow the radio boxes to toggle on of.
$("input[type=radio]").click(function(){
$(this).attr("checked", !$(this).attr("checked"));
});
Edit:
I did a js fiddler with a working example, maybe it will give some answers.
http://jsfiddle.net/uPp82/1/
I was trying to code jquery/JS logic for hide/show description based on radio button being checked or not. If the radio button is checked on page load, i want the description associated with that radio button to load. But the default one of the either has to selected/checked
I did try to code with .change and click methods inside ready(). But was not successful
I have only two radio buttons, I'm not a Javascript/jquery person. Any input is appreciated. This is an example
<div id="ServiceSelection">
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivB" style="display:none" class="desc">B Description goes here </div>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>
</div>
Edited DIV:
<div id="ServiceSelection">
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<div id="DivB" style="display:none" class="desc">B Description goes here </div>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>
</div>
Thanks in advance
J
if($('input[name=Service]').is(':checked')){ //is it checked?
var v = $('input[name=Service]:checked').val(); //get the value
$('div[id$='+v+']').show(); //target the end of selector, and match it to our value
}
$('input[name=Service]').on('click', function(){
$(this).parent().find('div').hide(); //hide the divs...
$('div[id$='+$(this).val()+']').show(); //show the div based on our value again..
});
fiddle
Try this:
function ShowData(evt) {
var val = $("input[name=Service]:checked").val();
if (val == 'B') {
$('#DivB').show();
$('#DivP').hide();
} else {
$('#DivP').show();
$('#DivB').hide();
}
}
$('input[name=Service]:radio').change(ShowData);
ShowData();
DEMO HERE
I'd suggest:
// hide the div elements with JavaScript, so they're visible to those
// users with JavaScript disabled:
$('#ServiceSelection div[id]').hide();
// select the radio input elements and bind to the change event
$('input:radio').change(function(){
// find the element whose id is equal to 'Div' + the value of the radio,
// show that div, hide the sibling div elements
$('#Div' + this.value).show().siblings('div').hide();
// filter the radio elements to find the one that's checked, and trigger the change event
}).filter(function(){return this.checked; }).change();
JS Fiddle demo.
References:
change().
filter().
hide
().
show().
siblings().