input radio does not hide content when unchecked, i can't make the content be hidden when the radio input is unchecked
how can I hide the content of the unmarked radio input?
clicking on another radio input is unchecked but does not hide the content
$('#alternar').click(function () {
$('#prueba').toggle();
});
$('#alternarx').click(function () {
$('#pruebax').toggle();
});
/* commented out because this select doesn't appear in the HTML:
$(".placeholder").select2({
placeholder: "Make a Selection",
allowClear: true
});
*/
function uncheckAndCheck(event) {
// gets all radios with the name prefix like 'custom-radio-'
// and uncheck all of them
document.querySelectorAll("input[type='radio'][name^='custom-radio-']").forEach(radio => {
radio.checked = false;
});
// checks the radio that triggered the click event
event.target.checked = true;
}
#prueba{
display:none
}
#pruebax{
display:none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>
<div id="prueba"> Content1 </div>
<input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>
<div id="pruebax"> Content2 </div>
George's solution works, but is reliant upon the HTML never changing. If you add any element between the radio button and the div, it will break the functionality.
To answer your question related to JavaScript:
It's unnecessary to check and uncheck the other radio inputs. You just need to give them the same name attribute.
Second, you're .toggle()ing the divs on click. That might be why they're acting strangely. You're not checking if the radio button is selected or not, and that's going to result in them toggling even when you click them when they're already selected. Luckily, you can just listen for them to change states.
Third, you can hold a selector for the target of the radio button you want to show/hide in a data attribute, and use one function for all of this.
Fourth, why mix inline onclick attributes, when you're using jQuery? Just listen for the event using the built-in listeners in jQuery.
//jQuery shorthand for $(document).ready(function(){ to be sure your DOM has loaded:
$(function() {
//run this on page load, too. Necessary because browsers will remember which one is checked on a page *refresh*, and hides the target divs initially when nothing is checked:
$checkedRB = $(".rbToggleDiv:checked");
if($checkedRB.length > 0) {
toggleVisibleDivs($checkedRB);
} else {
toggleVisibleDivs(false);
}
//both radio buttons have the same class as well, so you can listen for either of them to change states:
$(document).on("change", ".rbToggleDiv", function(e) {
//this = radio button that has changed
var $thisRB = $(this); //turn it into a jQuery object
if($thisRB.prop("checked")) { //only do something if this RB is checked
toggleVisibleDivs($thisRB);
}
});
function toggleVisibleDivs($targetRB) {
if ($targetRB === false) { //no target sent in
//hide all
$(".pruebaDiv").hide(); //hide all divs
} else { //target sent in
if ($targetRB.data("target-div")) { //make sure the data is set
var targetSelector = $targetRB.data("target-div"), //grab the string from the data object
$targetDiv = $(targetSelector); //use it to select the target div
if ($targetDiv.length > 0) { //make sure the div is selected
//hide all divs with the same class:
$(".pruebaDiv").hide();
//then, show only the one you want visible, the $targetDiv:
$targetDiv.show();
} else {
console.error("Div not found!", targetSelector);
}
} else {
//data not set:
console.error("Data was not set.");
}
}
}
});
.pruebaDiv {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- if they have the same names, they will act as a radio button list, and will act accordingly. Also, you should really choose more descriptive IDs and names: -->
<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternarx" data-target-div="#prueba" />
<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternar" data-target-div="#pruebax" />
<!-- for the sanity of the user, I've moved these two divs next to each other below the radio buttons so they don't move around: -->
<div class="pruebaDiv" id="prueba"> Content1 </div>
<div class="pruebaDiv" id="pruebax"> Content2 </div>
This is actually possible entirely with CSS. You can use the adjacent sibling combinator +, which affects an element immediately following the first.
#prueba{
display: none;
}
#pruebax{
display: none;
}
input:checked + #prueba,
input:checked + #pruebax {
display: block;
}
<input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>
<div id="prueba"> Content1 </div>
<input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>
<div id="pruebax"> Content2 </div>
Related
So I'm building a form in HTML that makes use of a lot of checkboxes and hidden Divs. Right now I'm using
function HideDiv1() {
var checkBox = document.getElementById("Check1");
var div = document.getElementById("Div1");
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
<input type="checkbox" id="Check1">CheckBox to show Div1
<div id="Div1" style="display: none;">I should be hidden, assuming the author didn't mess up!</div>
To hide each div based on the appropriate checkbox. But this means that I am copying and rewriting this function every time and the section where I like to keep my functions is getting quite large. I was wondering if there was an easier way to do this such that I would only need one function and I could dynamically show and hide Divs without needing to copy and rewrite this function every time.
(If there is some easy JQuery solution to this: please keep in mind that I have no clue how to use JQuery)
This may be a duplicate, I saw the answer once before in the past but I have no idea how to find it again :(
You can use data attributes to identify which div to show when the checkbox is changed.
You can do this by listening for the change event on each checkbox and toggling the corresponding div with jQuery.toggle:
$('input[type=checkbox]').change(function(){
$('div[data-id='+$(this).data('target')+']').toggle()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
Vanilla JS implementation:
document.addEventListener('click', function(e){
if(e.target.matches('input[type=checkbox]')){
let target = document.querySelector('div[data-id="'+e.target.dataset.target+'"]');
target.style.display = target.style.display == "none" ? "block" : "none";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
You would add an onchange attribute to the checkbox to call a single function called hideDiv and pass it two arguments that are the ids of the checkbox and the div that you are hiding with that checkbox:
onchange="hideDiv("check1","div1")"
...then hideDiv uses the arguments passed to it to toggle the correct div:
function hideDiv(checkId, divId) {
const checkbox = document.getElementById(checkId)
const div = document.getElementById(divId);
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
Get in the habit of using let for variables that you need to change and const for variables that will not change value instead of var.
I know this question has been asked plenty of times before, but I haven't been able to find a solution that works for my specific case.
So I have a radio button which I create statically initially. The HTML code is given below
<body>
<div class = 'container'>
<div class = 'row'>
<div class = 'col-md-8 col-md-offset-2 well'>
<div class = 'col-md-4'>
<h1>Title Placeholder</h1>
<p>My vote goes to</p>
In the below div is where I create the first static radio button
<div class = 'radio'>
<label>
<input type = 'radio' value = '1' name = 'options' class = 'radio-options'/>
<p id = 'radio1'>The value of 1</p>
</label>
</div>
<button type = 'submit' class = 'btn btn-primary submit-butt'>Submit</button>
</div>
</div>
</div>
</div>
</body>
Below is the section of the javascript file where I create dynamic radio buttons
function createOptions(length, options){
$('#radio1').html(options[0]);
for (var i = 1; i < length; i++){
$('.radio').append('<br>');
$('.radio').append('<label><input type = radio value = 1 name = options class = radio-options/><p>'+options[i]+'</p></label>');
}
$('.radio').append('<br>');
$('.radio').append('<label><input type = radio value = 1 name = options class = radio-options/><p>Custom</p></label>')
}
Now, when I click the submit button, with one of the radio buttons checked, I want to be able to know which of the radio buttons is checked and also the p value contained within its input tags
$('.submit-butt').on('click', function(){
if($('.radio-options').is(':checked')){
console.log('I have my value');
}
});
I tried the above code, but it only seems to work for the first statically created radio button. How do I get this same functionality to work for all the radio buttons, both statically and dynamically generated?
as long as your form is only deal with one set of radio buttons you can do it this way just change formId to whatever class/id you are using for the form wrapping the radios.
$('input[name=radioName]:checked', '#formId').val()
$('.submit-butt').on('click', function(){
var selectedRadioValue = $('input[name=radioName]:checked','#formId').val()
console.log(selectedRadioValue)
});
this is how you can do it. refer the working demo.
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#dynamicradio{
margin-left: 100px;
}
#clickme{
margin-left: 100px;
margin-top:10px;
}
</style>
<body>
<div id="dynamicradio"></div>
<input type="button" value="submit" id="clickme">
</body>
<script type="text/javascript">
// here we create the dynamic radio button.
var create_dynamic_radio = $("<input type='radio' id='myradioo'> <label> My Radio Button</label>")
$("#dynamicradio").append(create_dynamic_radio);
// here we write the code for click function.
$("#clickme").click(function(){
var isradiochecked = $("#myradioo").prop('checked');//check whether the dynamic radio button is checked or not.
if(isradiochecked == true)
{
alert("dynamic radio button is checked");
}
else
{
alert("dynamic radio button isn't checked");
}
});
</script>
</html>
I will start by telling you that this is my very first Javascript program from scratch. I am trying to make a back button that will go to the previously chosen div in a form (hide the current div and show the previous one the user chose).
The form has multiple paths to follow, paths within paths and not all selectors are buttons. There might be an onchange event or a radio button or even text input (text inputs have a next button to click).
I have had it working where it will hide the current div but show all previous chosen divs. It's now working where it hides the current div but shows nothing.
I have read a bunch of postings here and in other forums but have not found what I need yet. Any help would be greatly appreciated.
You can see the actual site here and I have put up a JSfiddle but for some reason I can't get it working there.
Here is the code from the fiddle:
<div>
<form>
<div id="uno" class="showFirst">
<button onclick="hideUno()">First Button</button>
</div>
<div id="dos" class="hideFirst">
<button onclick="hideDos()">Second Button</button>
</div>
<div id="tres" class="hideFirst">
<button onclick="hidetres()">Third Button</button>
</div>
<div id="quattro" class="hideFirst">
<button onclick="hideQuattroUno()">Fourth Button</button>
<button onclick="hideQuattroDos()">Fifth Button</button>
</div>
<div id="branchUno" class="hideFirst">
<p>First Branch</p>
</div>
<div id="branchDos" class="hideFirst">
<p>Second Branch</p>
</div>
</form>
<button id="backButton" onclick="goToPrevious" class="hideFirst">Back</button>
</div>
.hideFirst {
display: none;
}
function goToPrevious() {
var current = $(".chosen").find(":visible");
$(current).hide();
$(current).prev(".chosen").show();
}
function hideUno() {
$("#backButton").toggle();
$("#uno").toggle();
$("#uno").addClass("chosen");
$("#dos").toggle();
}
function hideDos() {
$("#dos").toggle();
$("#dos").addClass("chosen");
$("#tres").toggle();
}
function hideTres() {
$("#tres").toggle();
$("#tres").addClass("chosen");
$("#quattro").toggle();
}
function hideQuattroUno() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchUno").toggle();
}
function hideQuattroDos() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchDos").toggle();
}
Here are a few of the questions I've reviewed here:
retain show / hide div on multistep form
Hide and Show div in same level
how to show previous div of clicked div in angular.js
show div and hide existing div if open with jQuery?
Show one div and hide the previous showing div
I realize it's not the cleanest code, but as I said this is my first and I am trying to cleanup as I go along and learn new things.
You could make a bit of automatization instead of creating onclick events for each button/select separately.
For "Back" functionality, I'd use an array to store elements "on the fly" at each step, instead of checking visibility later on.
I'll make it this way:
Remove CSS rule display:none for hideFirst class (elements will be hidden using jQuery).
Add an class to the buttons/selects/check-boxes/etc... as event inndicator.
Add data-next attribute (to store id of the element which should be shown on click/change)
HTML:
<div id="firstDiv" class="hideFirst">
<button class="my-btn" data-next="#secondDiv" type="button">Show next<button>
</div>
<div id="secondDiv" class="hideFirst">
<select class="my-select" data-next="#thirdDiv">
<option>Helo World</option>
...
</select>
</div>
...
Script:
$(document).ready(function(){
// hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();
// declare 'history' variable as an empty array (it will be used to store 'hideFirst' elements for 'Back' functionality):
var history = [];
// click event for the buttons :
$('.my-btn').click(function(e){
// as the button will submit the form if you're not using type="button" attribute, use this:
e.preventDefault();
showNext($(this));
});
// change event for selects :
$('.my-select').change(function(){
showNext($(this));
});
// Method used to show/hide elements :
function showNext(el){
// check if element has a 'data-next' attribute:
if(el.data('next')){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// show 'Back' button:
$('#backButton').show();
// show the element which id has been stored in 'data-next' attribute:
$(el.data('next')).show();
// Push the parent element ('.hideFirst') into history array:
history.push(el.closest('.hideFirst'));
}
}
// click event for 'back' button:
$('#backButton').click(function(){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// remove the last '.hideFirst' element from 'history' array and show() it:
history.pop().show();
// hide 'back' button if history array is empty:
history.length || $(this).hide();
}).hide(); // hide 'back' button on init
});
DEMO
I have checkboxes that are hidden. I have images as the labels for the checkboxes, so that when the images are clicked the checkboxes are clicked. I am trying to make it so that the image has different opacities depending on whether the box is checked or not. Here is my css for the image label:
.checkbox-label{
opacity: .2;
}
.checkbox-label:hover{
opacity: .5;
}
.checkbox-label-after-click{
opacity: 1;
}
Here is my javascript to move the classes
<script>
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.checked){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
</script>
Basically, when someone clicks on the label, it should grab the next input, which is the checkbox, the label's classes should change. I've also tried switching the addClass and removeClass methods, which makes the class switch work on the first click, but never after.
Here is the html:
How do I get this to work?
I would do this with pure CSS, like this:
label {
cursor: pointer;
}
/* Change cursor when the label is hovered */
input[type=checkbox] {
display: none;
}
/* Hide the ugly default radio styling */
label > span {
opacity: 0.2;
}
/* Hide the checkmark by default */
input[type=checkbox]:checked + span {
opacity: 1;
color: green;
}
/* Show the checkmark when the radio is checked */
<label>
<input type="checkbox" name="obvious"><span>✓</span> I look good.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> Cause we've been re-styled!</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> I've got a green checkmark if you click me.</label>
<br/>
<label>
<input type="checkbox" name="obvious"><span>✓</span> We are a family of checkmarks!</label>
You can simply use toggleClass(). Your code is not working as the_input is a jQuery object and it doesn't have checked property. You can use .get() to get underlying DOM element.
like
the_input.get(0).checked or the_input[0].checked
As per your code
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click", the_input.get(0).checked ); //You can also use the_input.prop('checked')
});
Im guessing its falling down when checking its checked. You will be better off just toggling the class when you click the label
$('.checkbox-label').click(function(){
$(this).toggleClass( "checkbox-label-after-click" );
});
If you really want to check its state, you could do something like this:
$('.checkbox-label').click(function(){
var the_input = $(this).next('input');
if(the_input.prop('checked')){
$(this).addClass( "checkbox-label-after-click" );
} else {
$(this).removeClass("checkbox-label-after-click");
}
});
Use the_input.prop('checked') to see if the input is checked or not. It returns a boolean.
As the_input is a jquery object you cannot use checked property of javascript, you may use the_input[0].checked or use prop method.
Replace this:
if(the_input.checked){
With this:
if(the_input.prop('checked')){
Ideally, I want to have 2 toggler. When click the fieldset toggler, the fieldset shows up with a div inside being hidden. When an event happened or When click the div toggler, the div show up.
I can only manage one of the 2 toggler working.
This is the html
click here
<fieldset class="fieldset" style="display:none">
<input>//first inputs
<input> 2nd input
<input id="edit-text" name="custom-text" type="checkbox value=""/>
<div id="wrapper">include several fields that initially hidden</div>
</fieldset>
This is the toggler for the fieldset:
$("a.fieldset-toggle-trigger").click(function() {
$(".fieldset").toggle();
}
The div toggler is inside another groups of code:
var e_fields = $("div#wrapper");
//fadein/fadeout with an event:
function bindEditTextClick(){
$("input#edit-text").click( function() {
if ($(this).attr('checked')) {
e_fields.fadeIn(750);
} else {
e_fields.fadeOut(750, function() {
});
}
});
}
//toggle as a part of another live click fuunction:
if (e_fields.is(':visible')) {
e_fields.fadeOut(500);
}
If I let the fieldset initially loaded as visible, the inside toggle works fine. This inside toggle is connected to other events, not easy to modify. How can I modify the fieldset toggler to allow inside toggle continue working?
If I get you correct you want to toggle main section and then toggle inner section depends on checkbox state. Is so, code and working solutions are below:
html
click here
<fieldset class="fieldset">
<input /><br />
<input /><br />
<input id="edit-text" name="custom-text" type="checkbox" value=""/>
<div id="wrapper">include several fields that initially hidden</div>
</fieldset>
css
fieldset { display:none; }
#wrapper { display:none; }
js
$(function() {
$(".fieldset-toogler-trigger").click(function() {
$(".fieldset").toggle();
});
$("#edit-text").change(function() {
var action = 'fadeOut';
if ($(this).is(':checked')) {
action = 'fadeIn';
}
$('#wrapper')[action](750);
});
});
jsfiddle
http://jsfiddle.net/y7PKk/
Got the solution for toggle the entire fieldset without messing up the inside toggle:
Initially move away the fieldset instead of hide the fieldset:
.moveaway{
position:absolute;left:-999em;
}
Then, use the fieldset toggler to toggle the moveaway class on/off.