Fade on Checkbox for Multiple Div Sections - javascript

I have a client that wants to have a checkbox that says "Mark as Compete" and once marked it makes the div with content fade. They basically want a step by step list like a recipe where users can check the box when they are done with a step and have it fade out.
I have been able to do so but not in a friendly way that someone who doesn't know code would be comfortable with editing. I am looking for some help simplifying it.
Current Code:
function ShowHideDivOne(chk_one) {
var one = document.getElementById("one");
one.style.opacity = chk_one.checked ? "0.5" : "1";
}
function ShowHideDivTwo(chk_two) {
var two = document.getElementById("two");
two.style.opacity = chk_two.checked ? "0.5" : "1";
}
function ShowHideDivThree(chk_three) {
var three = document.getElementById("three");
three.style.opacity = chk_three.checked ? "0.5" : "1";
}
div {font-wieght:bold;font-size:30px; margin-top:30px;}
<div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="ShowHideDivOne(this)"/>Mark as done
<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="ShowHideDivTwo(this)"/>Mark as done
<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="ShowHideDivThree(this)"/>Mark as done
Right now if they wanted to add a "Four," I would have to have the ShowHideDivFour(chk_four) function preprogrammed and then they would have to go in and change all of the ids and onclicks in the div and the checkbox.
I am ok with showing them how to edit the id in the div. What I would prefer is to have a JavaScript code that works for an unlimited number of items in their list and they would only have to change the div id. I understand if they would also have to change the checkbox code but it would be preferable if they didn't.
Any help would be much appreciated.

If, somehow, your headers can come after the checkboxes, you can use the CSS sibling + selector to select it:
div {
font-size: 30px;
margin-bottom: 30px;
}
input:checked+div {
opacity: 0.5;
}
<label for="chk_one">Mark as done</label>
<input type="checkbox" id="chk_one" />
<div id="one">One</div>
<label for="chk_two">Mark as done</label>
<input type="checkbox" id="chk_two" />
<div id="two">Two</div>
<label for="chk_three">Mark as done</label>
<input type="checkbox" id="chk_three" />
<div id="three">Three</div>
Here is a complete, CSS-only solution that uses the above and a little CSS flexbox hack to reverse the display order of the header and checkbox, if you're fine with wrappers:
div.wrapper {
display: flex;
/* 👇 display elements in reverse order */
flex-direction: column-reverse;
}
div.item {
font-size: 30px;
margin-top: 30px;
}
input {
width: fit-content;
}
input:checked~div {
opacity: 0.5;
}
<!-- 👇 notice that the checkboxes come BEFORE
the text, but are displayed as if they are after -->
<div class="wrapper">
<label for="chk_one">Mark as done</label>
<input type="checkbox" id="chk_one" />
<div id="one" class="item">One</div>
</div>
<div class="wrapper">
<label for="chk_two">Mark as done</label>
<input type="checkbox" id="chk_two" />
<div id="two" class="item">Two</div>
</div>
<div class="wrapper">
<label for="chk_three">Mark as done</label>
<input type="checkbox" id="chk_three" />
<div id="three" class="item">Three</div>
</div>
Any "normal" solution (not as hacky as this) would only be attainable through JavaScript.
EDIT: if you're OK with using JS, here's something that looks marginally better by using direct element references in inline event listeners:
div {
font-size: 30px;
margin-top: 30px;
}
<div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="one.style.opacity = (one.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_one">Mark as done</label>
<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="two.style.opacity = (two.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_two">Mark as done</label>
<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="three.style.opacity = (three.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_three">Mark as done</label>

You can simplify the code by adding a class name to the checkbox and adding an event listener to all elements of that class:
document.querySelectorAll('.markChk').forEach(el => {
el.addEventListener('click', function(event) {
var divID = this.parentElement.previousElementSibling;
divID.style.opacity = el.checked ? "0.5" : "1";
});
});
div {font-weight: bold; font-size: 30px; margin-top: 30px;}
<div id="one">One</div>
<label><input type="checkbox" id="chk_one" class="markChk" /> Mark as done </label>
<div id="two">Two</div>
<label><input type="checkbox" id="chk_two" class="markChk" /> Mark as done </label>
<div id="three">Three</div>
<label><input type="checkbox" id="chk_three" class="markChk" /> Mark as done </label>
Notes:
this.parentElement.previousElementSibling traverses from the checkbox to the previous div
notice the <label>, which allows the user to click on the label, not just the checkbox
to further simplify you likely want to generate the div and checkbox list dynamically
jQuery makes it easier than native JS to manipulate the DOM

Related

javascript radio button form

I'm new to javascript and am trying to write a simple script that will open 1 form upon checking a radio button, and another form upon clicking on the second one (none when none is selected).
I'm positive the js code is totally wrong as I am a COMPLETE beginner with js, but I used logic and a bit of google to get to this, and I don't know where I went wrong.
var ele1 = document.getElementsByClassName("form1");
var ele2 = document.getElementsByClassName("form2");
if (document.getElementById('button1').checked)
{
ele1.style.display = "block";
}
if (document.getElementById('button2').checked)
{
ele2.style.display = "block";
}
.form1 {
display: none;
background-color: red;
width: 100px;
height: 100px;
}
.form2 {
display: none;
background-color: blue;
width: 100px;
height: 100px;
}
<input type="radio" name="role" id="button1">
<input type="radio" name="role" id="button2">
<div class="form1">
</div>
<div class="form2">
</div>
<script src="/scripts/form.java"></script>
This code isn't wrong as such, but it only ever executes once; when the page loads. You instead want the forms to be toggled whenever the inputs are changed.
To do this, the visibility code is wrapped in a function. This function is then registered as an event handler on the <input> elements so that it executes whenever the <input>s change. Whenever the selected radio button changes, by clicking or by keyboard navigation, an 'input' event will be triggered on the elements, and then handled by the function.
I've also made a few other changes:
Use only ids since this is specific functionality for a handful of specific elements.
Use <form> elements for better semantics. All forms must be wrapped in a <form> element at some level.
Change .java to .js – JavaScript and Java are (unintuitively) unrelated.
Change the name on the <input>s to better describe their role.
<input type="radio" name="formID" id="input1">
<input type="radio" name="formID" id="input2">
<form id="form1">
<!-- fields -->
</form>
<form id="form2">
<!-- fields -->
</form>
<script src="/scripts/form.js"></script>
// form.js
// Get references to important elements.
var elInput1 = document.getElementById('input1');
var elInput2 = document.getElementById('input2');
var elForm1 = document.getElementById('form1');
var elForm2 = document.getElementById('form2');
// Define an event handler function.
function updateFormVisibility(event) {
var elSelectedInput = event.target;
if (elSelectedInput.id === 'input1') {
elForm1.style.display = 'block';
elForm2.style.display = '';
} else {
elForm1.style.display = '';
elForm2.style.display = 'block';
}
}
// Register the function as a handler for any `'input'` events that occur on the
// two radio button elements.
elInput1.addEventListener('input', updateFormVisibility);
elInput2.addEventListener('input', updateFormVisibility);
According to #Mehdi Brillaud's answer here: https://stackoverflow.com/a/42488571/13695248, you could try this with JQuery:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="red" data-id="a" checked> red</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="green" data-id="b"> green</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="blue" data-id="c"> blue</label>
<div class="form form-a active"> form a </div>
<div class="form form-b"> form b </div>
<div class="form form-c"> form c</div>
.form {
display: none;
}
.form.active {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.form-switch').on('change', function() {
$('.form').removeClass('active');
var formToShow = '.form-' + $(this).data('id');
$(formToShow).addClass('active');
});
});
</script>
Is this what you want?
For modern browsers:- (Not recommend)
<input type="radio" name="role" id="button1" onchange = "form1.style.display ='block'; form2.style.display ='none'">
<input type="radio" name="role" id="button2" onchange = "form1.style.display ='none'; form2.style.display ='block'">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
Update
Recommend
<input type="radio" name="role" id="button1" onchange = "Show('form1')">
<input type="radio" name="role" id="button2" onchange = "Show('form2')">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
<script>
var selected = document.getElementById("form1");
function Show(curr_sel) {
selected.style.display = "none";
   selected = document.getElementById(curr_sel);
   selected.style.display = "block";
}
</script>

get the selected dropdown value in the inputfield instead of placeholder using javascript

I want dropdown with radio button which needs to show when I click field and hide when I click outside and get the selected value in the inputfield. I have partially working code.
I am not able to hide the dropdown, once it got opened.
I need the selected value in the input field instead of placeholder value which I have.
I see lot of answer's for the select option dropdown but not for the tag placeholder.
//Not sure why the above function is not hiding the dropdown
RadioDdOnclick() {
var x=document.getElementById("radiobtn");
if (x.style.display==="none") {
document.getElementById('RadioDd').style.visibility='hidden'; //i tried style.display ='none';
}
else {
document.getElementById('RadioDd').style.display='block';
}
}
<div className="inputWithIcon" onClick={this.RadioDdOnclick} id="radiobtn">
<input className="inputBlock" id="radioSelect" type="text" placeholder="choose one" />
<i className="fa fa-angle-down" />
</div>
<div className={ "BudgetRadioDd"} id={ "RadioDd"} style={{display: 'none'}}>
<fieldset>
<h4>options to choose</h4>
<div>
<label><input type="radio" id="1"/>option 1</label>
</div>
<div>
<label> <input type="radio" id="2" />option 2</label>
</div>
<div>
<label><input type="radio" id="3"/>option 3</label>
</div>
</fieldset>
</div>
//css code here
.input[type=text]{
width:100%;
border:2px solid #aaa;
border-radius:4px;
margin:8px 0;
outline:none;
padding:8px;
box-sizing:border-box;
transition:.3s;
}
.inputWithIcon{
position:relative;
}
.inputWithIcon i{
position:absolute;
right: 3%;
top: 0;
font-size: 25px;
padding: 20px 8px;
color:#c69937;
transition:.3s;
}
update
Below answer is working but it is rendering the radio value in another div component.
Looking for better solution..
adding the link to look at the issue: https://stackblitz.com/edit/react-feubq6?file=index.js
I updated your code and simplified it to HTML for simplicity. Please check:
function RadioDdOnclick(event) {
const hovered = document.querySelectorAll(':hover');
if (hovered[hovered.length - 1].type !== 'radio') {
const x = document.querySelector('#RadioDd');
const toggleMap = {
none: 'block',
block: 'none'
};
x.style.display = toggleMap[x.style.display];
}
}
document.querySelectorAll('[type=radio]').forEach(r => {
r.onclick = _ => {
if (r.checked) {
document.querySelector('#radioSelect').value = r.value;
}
document.querySelector('#RadioDd').style.display = 'none';
}
});
<div class="inputWithIcon" id="radiobtn">
<input className="inputBlock"
id="radioSelect"
type="text"
onClick="RadioDdOnclick(event)"
onBlur="RadioDdOnclick(event)"
placeholder="choose one" />
<i className="fa fa-angle-down" />
</div>
<div class="BudgetRadioDd" id="RadioDd" style="display: none">
<fieldset>
<h4>options to choose</h4>
<div>
<label>
<input name="budget" type="radio" id="1" value="option 1"/>
option 1
</label>
</div>
<div>
<label>
<input name="budget" type="radio" id="2" value="option 2"/>
option 2
</label>
</div>
<div>
<label>
<input name="budget" type="radio" id="3" value="option 3"/>
option 3
</label>
</div>
</fieldset>
</div>

CSS hide div with radiobutton outside form

I am trying to hide a div through css.
The div hide is working inside the form, how can this be done outside the form, or even outside the div row?
HTML
<div class="row">
<form>
<input type="radio" name="radio" value="show" checked/>Show <br>
<input type="radio" name="radio" value="hide"/>Hide
<div class="hideDiv">
<p>Can you see me</p>
</div>
</form>
</div>
CSS
input[type=radio][value="hide"]:checked ~ .hideDiv {
display: none;
}
Preferably only css but javascript is also a option.
Use less CSS specificity.
.hideDiv {
display: none;
}
maybe something similar to this code will help?
<input type="radio" name="radio" onclick="hideFunc();" value="show" checked/>Show <br>
<input type="radio" name="radio" onclick="hideFunc();" value="hide"/>Hide
<script>
hideFunc = function() {
if (document.getElementsByClassName('hideDiv')[0].style.display == "none")
document.getElementsByClassName('hideDiv')[0].style.display = "block";
else
document.getElementsByClassName('hideDiv')[0].style.display = "none";
}
</script>
You could try this:
favorite
I am trying to hide a div through css. The div hide is working inside the form, how can this be done outside the form, or even outside the div row?
HTML
<div class="row">
<form>
<input type="radio" name="radio" value="show" onclick="hideDiv();" checked/>Show <br>
<input type="radio" name="radio" onclick="hideDiv();" value="hide"/>Hide
<div class="hideDiv">
<p>Can you see me</p>
</div>
</form>
</div>
JS
function hideDiv() {
var aux = $('input[name="radio"]:checked').val();
if (aux == 'show'){
$('.hideDiv').css("display","block");
}else{
$('.hideDiv').css("display","none");
}
}
you can do it easily using jquery
$('.chkToogle').click(function(){
$('.hideDiv').fadeToggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<form>
<input type="checkbox" class="chkToogle" checked/>Show/Hide
</form>
</div>
<div class="hideDiv">
<p>Can you see me</p>
</div>

Disable all previous checkboxes except last one, enable preceding checkbox when other enabled

I've searched a while for this, but can't find a solution. Basically, I have a simple form, that will by dynamic (up to 20 cycles can exist for an ID). The validation to delete the Cycles, say that there are 3 of them, 1, 2, and 3, is that you can delete #3, but you cannot delete #2 until you delete #3, and you cannot delete #1 until you delete #2.
So, on the front-end, I was thinking of a design that would disable all but the last checkbox, then as you check the last checkbox, the next previous checkbox would be enabled and be able to be checked, and so on. Then, the user would delete (through a Bootbox modal submit button callback, which is even a bit trickier).
Here's a simple form I was using to test with:
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox"><label><input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label></div>
<div class="checkbox"><label><input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label></div>
<div class="checkbox"><label><input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label></div>
</div>
</form>
How can you dynamically write JavaScript (I'm using jQuery 1.12.4) to achieve this? I'm hoping to have something in the ID's that can almost make a chain of enabling the checkboxes -- the last one being enabled by default since it's not dependent on others to be deleted, but, then enabling the other checkboxes on the fly as the one above it is enabled.
Can anyone help with this?
Thanks so much!
So you can do this using jquery:
Initially set all but the last checkbox disabled
Use a checkbox listener that will:
a. enable the preceeding checkbox on ticking
b. disable all preceeding checkbox when unticking
See demo below:
// Initialize : disable all but the last checkbox
$('#deleteCycles .checkbox:last').prevAll().each(function() {
$(this).find('input').attr('disabled', 'disabled');
});
// checbox listener
$('#deleteCycles .checkbox input').change(function() {
if ($(this).is(":checked")) {
// enable the checkbox just above
$(this).closest('.checkbox').prev('.checkbox').find('input').removeAttr('disabled');
} else {
// disable all checkboxes preceeding
$(this).closest('.checkbox').prevAll().each(function() {
$(this).find('input').attr({
'disabled': 'disabled',
'checked': false
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox">
<label>
<input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label>
</div>
<div class="checkbox">
<label>
<input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label>
</div>
<div class="checkbox">
<label>
<input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label>
</div>
</div>
</form>
$(function () {
$(':checkbox').attr('disabled', true).each(function (index, element) {
$(this).data('index', index);
}).change(function () {
if($(this).is(':checked'))
{
$(this).parents('.checkbox:first').prev().find(':checkbox').attr('disabled', null);
}
else
{
$(this).parents('form:first').find(':checkbox:lt(' + $(this).data('index') + ')').attr('checked', false).attr('disabled', true);
}
}).last().attr('disabled', null);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox"><label><input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label></div>
<div class="checkbox"><label><input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label></div>
<div class="checkbox"><label><input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label></div>
</div>
</form>
Assuming sequential IDs, something like this might work.
Add a data-attribute that lets you reference the checkbox that the currently-active checkbox "depends on":
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox">
<label>
<input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes" />
Cycle 1
</label>
</div>
<div class="checkbox">
<label>
<input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes" data-dependsOn="#cycle1" />
Cycle 2
</label>
</div>
<div class="checkbox">
<label>
<input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes" data-dependsOn="#cycle2" />
Cycle 3
</label>
</div>
</div>
</form>
Then, when the checkbox is toggled, check both it's checkstate and the "depends on" checkbox's checkstate:
$('.dynamicCheckboxes').on('change', function(e){
// hold reference to the current checkbox
var _this = $(this);
if(!_this.is(':checked')){
var dependsOn = _this.data('dependsOn');
if(dependsOn != ""){
if($(dependsOn).is(':checked')){
e.preventDefault();
// display some sort of error message
}
}
}
});
You could use the jQuery .prev function, as well, if your markup supports it (if the dependent checkbox always precedes the checkbox you're checking, in the markup).

Need help to optimze a code for radio button

$('input[type="radio"]').change(function(){
if ($('#subscribe').is(':checked')){
$("#subNow").show();
$('#oneTime').hide();
}
if ($('#one-time').is(':checked')){
$('#oneTime').show();
$("#subNow").hide();
}
});
The above code is to show and hide 2 div's on click of 2 radio buttons. I am new to jquery so would like to know is there a better way to write this same functionality.
If you setup the initial state, say #subNow { display: none; }, then just use the .toggle() method, no conditions check what-so-ever...
$('input[type="radio"]').change(function(){
$("#subNow").toggle();
$('#oneTime').toggle();
});
#subNow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type='radio' name='rd' checked />1
<input type='radio' name='rd' />2
<br />
<div id="subNow">subNow</div>
<div id="oneTime">oneTime</div>
Also,
if perhaps they are followed on the markup, why not drop JS and go CSS-only??
input[type="radio"]:nth-child(2):checked ~ #oneTime,
#subNow
{
display: none;
}
input[type="radio"]:nth-child(2):checked ~ #subNow{
display: block;
}
<input type='radio' name='rd' checked />1
<input type='radio' name='rd' />2
<br />
<div id="subNow">subNow</div>
<div id="oneTime">oneTime</div>
This is exactly the way I would do this. The only other option would be to get the value of the radio buttons, but you'd essentially be doing the same thing that you already are.
One way is to use common classes and data attributes
$(".rads").on("change", '[type="radio"]', function (e) {
var show = $(this).data("show");
$(".details").hide().filter(show).show();
});
.details {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="rads">
<input type="radio" id="x" name="rad" data-show=".foo" />
<label for="x">A</label>
<input type="radio" id="y" name="rad" data-show=".bar" />
<label for="y">B</label>
</div>
<div class="foo details">Apple</div>
<div class="bar details">Bacon</div>
There is also pure CSS solutions using the :checked selector.
If you don't have any other states to worry about, you can cut the second if and place a else
$('input[type="radio"]').change(function(){
if ($('#subscribe').is(':checked')){
$("#subNow").show();
$('#oneTime').hide();
}
else{
$('#oneTime').show();
$("#subNow").hide();
}
});
You can also use switch

Categories

Resources