Can I do a toggling loop with Javascript alone? - javascript

I have this simple HTML and Javascript, and it works very well. My question is, is there a way to do it with loops?
I don't want to use jQuery -- just plain Javascript, please!
<form action="">
<input type="radio" name="r" onclick="func();" id="r1">
<input type="radio" name="r" onclick="func();" id="r2">
<input type="radio" name="r" onclick="func();" id="r3">
<input type="radio" name="r" onclick="func();" id="r4">
</form>
<div id="sq" style=" width: 100px;
height: 100px;
background: #000;
display: none;"></div>
<div id="ci" style=" width: 100px;
height: 100px;
background: #555;
display: none;></div>
<div id="tr" style=" width: 100px;
height: 100px;
background: #888;
display: none;></div>
<script>
var r1 = document.getElementById("r1");
var r2 = document.getElementById("r2");
var r3 = document.getElementById("r3");
var sq = document.getElementById("sq");
var ci = document.getElementById("ci");
var tr = document.getElementById("tr");
var el = [sq, ci, tr];
var rs = [r1, r2, r3];
function func() {
if(r1.checked) {
sq.style.display = "block";
} else {
sq.style.display = "none";
}
if(r2.checked) {
ci.style.display = "block";
} else {
ci.style.display = "none";
}
if(r3.checked) {
tr.style.display = "block";
} else {
tr.style.display = "none";
}
}
</script>
You can check it out on codepen here.

Use addEventListener instead of inline event listeners. I refactored your code a bit:
const colors = ['black', '#777', '#BBB', 'white'];
const area = document.querySelector('div'); // find the <div> element
// find all <input type="radio"> elements
document.querySelectorAll('input[type="radio"]').forEach((input, index) => {
// add an event listener to the click event
input.addEventListener('click', () => {
// set the <div>'s background color
area.style.backgroundColor = colors[index];
});
});
div {
width: 100px;
height: 100px;
}
<input type="radio" name="r">
<input type="radio" name="r">
<input type="radio" name="r">
<input type="radio" name="r">
<div></div>

Try something like this:
for (var i=0; i<el.length; i++) {
if (rs[i].checked) {
el[i].style.display = "block";
} else {
el[i].style.display = "none";
}
}

Related

Clone div and delete div

I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
function appearafter2() {
document.getElementById("buttonappear2").style.display = "block";
document.getElementById("button2").style.display = "block";
document.getElementById("hinzufuegen2").style.display = "none";
}
function myFunction2() {
var itm = document.getElementById("myList4").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList3").appendChild(cln);
}
function deleteFunction2() {
var list3 = document.getElementById("myList3");
var divs = Array.from(list3.getElementsByTagName("div"));
// If the number of divs is 4, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 4) {
document.getElementById("button2").style.display = "none";
}
var lastDivToDelete2 = divs[divs.length - 1];
list3.removeChild(lastDivToDelete2);
}
function allFunction2() {
myFunction2();
appearafter2();
}
#button2 {
display: none;
}
#buttonappear2 {
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#myList3 {
display: none;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="allFunction2()">
+ Loc de munca
</div>
<div id="myList3">
<div id="button2" onclick="deleteFunction2()">Șterge</div>
<div id="myList4">
<div id="addingNewJob">
<label class="label-job-input" for="job-input-1">Numele firmei</label>
<select size="1" type="text" id="job-input-1" /><option value="scoala_generala">școala generală</option>
<option value="scoala">școală profesională</option>
<option value="lic">liceu</option>
<option value="fac">facultate</option></select>
<label class="label-job-input" for="job-input-2">Postul ocupat
</label>
<input size="1" type="text" id="job-input-3" /><br />
<label class="label-data2" for="job-input-3">din data</label><label class="label-data2" for="job-input-4">până la data</label><br />
<input type="number" style="width: 48%" />
<input type="number" style="width: 50%; margin-left: 6px" />
</div>
</div>
</div>
<div onclick="allFunction2()" id="buttonappear2">
+ Loc de munca
</div>
Hello, I don't understand why all Functions are not working. Normally if you click on the button "+ Loc de munca" needs to appear input and then if you click further on the "+ Loc de munca" need to clone all input. Also if you click on the "Sterge" need everything to delete. Here is the code:
Updated the answer, check if this is what you are trying to achieve.
function myFunction2() {
var cln = '<div class="list-item">'+
'<div id="addingNewJob">'+
'<label class="label-job-input" for="job-input-1">Numele firmei</label>'+
'<select size="1" type="text" id="job-input-1" /></div>';
document.getElementById("myList3").innerHTML+=cln;
document.getElementById("buttonappear2").classList.remove('hide');
document.getElementById("button2").classList.remove('hide');
document.getElementById("hinzufuegen2").classList.add('hide');
}
function deleteFunction2() {
var divs = Array.from(document.querySelectorAll(".list-item"));
if(divs.length>0){
var lastDivToDelete2 = divs[divs.length - 1];
document.getElementById("myList3").removeChild(lastDivToDelete2);
}
if(divs.length==1){
document.getElementById("buttonappear2").classList.add('hide');
document.getElementById("button2").classList.add('hide');
document.getElementById("hinzufuegen2").classList.remove('hide');
}
}
.hide{
display: none;
}
.input-data2 {
width: 49%;
}
.label-data2 {
width: 50%;
}
#label-job-input-inline {
display: inlin-block;
}
.label-job-input {
display: block;
}
<div id="hinzufuegen2" onclick="myFunction2()">+ Loc de munca</div>
<div id="myList3">
<div id="button2" class="hide" onclick="deleteFunction2()">Șterge</div>
</div>
școala generală școală profesională liceu facultate
<label class="label-job-input" for="job-input-2">Postul ocupat</label>
<form>
<input size="1" type="text" id="job-input-3" />
<br />
<label class="label-data2" for="job-input-3">din data</label>
<label class="label-data2" for="job-input-4">până la data</label>
<br />
<input type="number" style="width: 48%;" />
<input type="number" style="width: 50%; margin-left: 6px;" />
</form>
<div onclick="myFunction2()" class="hide" id="buttonappear2">+ Loc de munca</div>

How to change the text of a label when a radio button is selected

What I don't understand is why does my code not change the text of the label when the radio is selected?
This is what is suppose to happen:
Which when 'Fahrenheit to Celsius' is selected the first image should be true (the text of the first and second label should change)
When 'Celsius to Fahrenheit' is selected the second image should be true (the text of the first and second label should change)
What I'm guessing is my problem is with the if ($("input:to_celsius").val() == "true") statement but I don't quite know why it's wrong.
***Current error message:
{
"message": "Uncaught TypeError: Cannot set property 'onclick' of null",
"filename": "https://stacksnippets.net/js",
"lineno": 69,
"colno": 30
}
"use strict";
var $ = function(id) { return document.getElementById(id); };
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "true") {
$("#degree_labl_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
}
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "true") {
$("#degree_labl_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
<script src="jquery-3.4.1.min.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
There are multiple issues in your code.
Looks like you are trying to use jQuery here, but in your case you are overriding the jQuery $ function with a custom function. So in effect you are not using jQuery here by calling the $ function but using pure javascript selectors
var $ = function(id) {
return document.getElementById(id);
};
With a function declaration as above, you can select elements only by Id and the Id should not be prefixed with #
$("#degree_label_1") won't work here
$("degree_label_1") will work.
So I suggest changing the $ function declaration to something like below.
var $ = function(selector) {
return document.querySelector(selector);
};
Here I changed document.getElementById -> document.querySelector so that selectors are more flexible (You can use any css selectors like "#id", ".classname" etc)
As we are not using jQuery here, the below code will not work. In jQuery, its correct but there are syntax differences in accessing the dom in plain javascript
$("#to_fahrenheit").val() == "true"
One way to implement the same is..
Assign values to the radio button inputs
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br />
and check the value
$("#to_fahrenheit").value == "c_to_f"
Same applies to the below line. There's a typo as well (Missed an e in degree_label_1)
$("#degree_labl_1").text("Enter F degrees")
should be changed to
$("#degree_label_1").textContent = "Enter F degrees"
Complete code would look like below.
"use strict";
var $ = function(id) {
return document.querySelector(id);
};
var clearTextBoxes = function() {
$("#degrees_entered").value = "";
$("#degrees_computed").value = "";
};
window.onload = function() {
$("#to_celsius").onclick = toCelsius;
$("#to_fahrenheit").onclick = toFahrenheit;
$("#convert").onclick = convert;
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").value == "c_to_f") {
$("#degree_label_1").textContent = "Enter C degrees";
$("#degree_label_2").textContent = "Degrees Fahrenheit";
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").value == "f_to_c") {
$("#degree_label_1").textContent = "Enter F degrees";
$("#degree_label_2").textContent = "Degrees Celsius";
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).value;
var enteredValue = Number($("#degrees_entered").value);
if (conversiontype === "f_to_c") {
$("#degrees_computed").value = ((enteredValue - 32) * 5) / 9;
} else {
$("#degrees_computed").value = (enteredValue * 9) / 5 + 32;
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<h1>Convert temperatures</h1>
<input
type="radio"
name="conversion_type"
id="to_celsius"
value="f_to_c"
checked
/>Fahrenheit to Celsius<br />
<input
type="radio"
name="conversion_type"
id="to_fahrenheit"
value="c_to_f"
/>Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />
If you want to use jQuery, you should remove below function declaration
var $ = function(id) {
return document.getElementById(id);
};
And modify your code as follows.
"use strict";
var clearTextBoxes = function() {
$("#degrees_entered").val("");
$("#degrees_computed").val("");
};
window.onload = function() {
$("#to_celsius").on("click", toCelsius);
$("#to_fahrenheit").on("click", toFahrenheit);
$("#convert").on("click", convert);
$("#degrees_entered").focus();
};
// Change the text of label 1 and 2 when the radio 'Celsius to Fahrenheit' is selected and clears all other inputs
var toFahrenheit = function() {
if ($("#to_fahrenheit").val() == "c_to_f") {
$("#degree_label_1").text("Enter C degrees");
$("#degree_label_2").text("Degrees Fahrenheit");
clearTextBoxes();
}
};
// Change the text of label 1 and 2 when the radio 'Fahrenheit to Celsius' is selected and clears all other inputs
var toCelsius = function() {
if ($("#to_celsius").val() == "f_to_c") {
$("#degree_label_1").text("Enter F degrees");
$("#degree_label_2").text("Degrees Celsius");
clearTextBoxes();
}
};
var convert = function() {
var conversiontype = $(
'[name="conversion_type"]:checked'
).val();
var enteredValue = Number($("#degrees_entered").val());
if (conversiontype === "f_to_c") {
$("#degrees_computed").val(((enteredValue - 32) * 5) / 9);
} else {
$("#degrees_computed").val((enteredValue * 9) / 5 + 32);
}
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 0.5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: 0.5em;
}
#convert {
width: 10em;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" value="f_to_c" checked />Fahrenheit to Celsius<br />
<input type="radio" name="conversion_type" id="to_fahrenheit" value="c_to_f" />Celsius to Fahrenheit<br /><br />
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" /><br />
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled /><br />
<label> </label>
<input type="button" id="convert" value="Convert" /><br />

How to write code for counts prices from checked inputs

I started to learn javascript 2 weeks ago. I want to do my first program which counts all prices from checked input.
But i dont have idea how to do this.
I found something on internet and stackoverflow, but i dont know to do this for my inputs.
Could you help me?
My code
// this function counts all the values
function showPrice() {
var priceOne = document.getElementsByName('price1');
var priceTwo = document.getElementsByName('price2');
var priceThree = document.getElementsByName('price3');
}
You can do this by getting a list of elements for all the inputs, check the ones that are checked, get their values, convert them to numbers and sum them.
Beginning with a list of ids, use Array.map() to transform the list into a list of string ids (1 -> test1).
Then apply getElementById() to each id to get the HTML element.
Then from the element extract and convert the value if the input is checked, otherwise map the element to 0.
Use Array.reduce to sum the values.
Using getElementById, find your output span and set its innerHTML to the total.
function showPrice() {
const total = [1,2,3,4,5,6,7,8,9]
.map(id => `test${id}`)
.map(id => document.getElementById(id))
.map(el => el && el.checked ? Number(el.value) : 0)
.reduce((sum, value) => sum + value, 0);
document.getElementById('getPrice').innerHTML = total;
}
.priceInput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
.priceOutput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
<div class="priceInput">
<p>Part 1</p>
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="10">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="25">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="12">
</div>
<div class="priceInput">
<p>Part 2</p>
<label for="test4">test4</label>
<input type="radio" name="price2" id="test4" value="5">
<label for="test5">test5</label>
<input type="radio" name="price2" id="test5" value="7">
<label for="test6">test6</label>
<input type="radio" name="price2" id="test6" value="2">
</div>
<div class="priceInput">
<p>Part 3</p>
<label for="test7">test7</label>
<input type="radio" name="price3" id="test7" value="250">
<label for="test8">test8</label>
<input type="radio" name="price3" id="test8" value="720">
<label for="test9">test9</label>
<input type="radio" name="price3" id="test9" value="410">
</div>
<br>
<div class="priceOutput">
<button onclick="showPrice()">Show Price</button>
<p>Your Price is : <span id="getPrice">0<!--Here i want to get price1(value) + price2(value) + price3(value)--></span> $</p>
</div>
By looking at your code, it seems that you want to get the option the user selected out of the radio buttons and not all radio buttons (referring to the getElementsByName). To do so, you can go over the nodeList returned and see if any of the elements have the checked property.
for(let i = 0; i < priceOne.length; i++){
if(priceOne[i].checked) {
//Get value of the price selected with .value
let priceOneValue = priceOne[i].value;
}
}
After doing this for all your input types, you can sum them up.
JO_VA here is my own code. Can you check it? It's easier for my understanding.
I found just 1 problem and it is : when i remove from HTML input tag "checked" and i klikn only for 1 or 2 radio options, it show NaN in paragraph for price.
BTW sorry for my english (i ussually dont use english language)
function showPrice(){
var pricePlace = document.getElementById("getPrice");
getVal1();
getVal2();
getVal3();
var InputNumber = Number(inputVal1) + Number(inputVal2) + Number(inputVal3);
pricePlace.innerHTML = InputNumber;
}
var inputVal1;
function getVal1(){
var a = document.getElementById("test1");
var b = document.getElementById("test2");
var c = document.getElementById("test3");
if (c.checked) {
inputVal1 = c.value;
}
if (b.checked) {
inputVal1 = b.value;
}
if (a.checked) {
inputVal1 = a.value;
}
}
var inputVal2;
function getVal2(){
var a = document.getElementById("test4");
var b = document.getElementById("test5");
var c = document.getElementById("test6");
if (c.checked) {
inputVal2 = c.value;
}
if (b.checked) {
inputVal2 = b.value;
}
if (a.checked) {
inputVal2 = a.value;
}
}
var inputVal3;
function getVal3(){
var a = document.getElementById("test7");
var b = document.getElementById("test8");
var c = document.getElementById("test9");
if (c.checked) {
inputVal3 = c.value;
}
if (b.checked) {
inputVal3 = b.value;
}
if (a.checked) {
inputVal3 = a.value;
}
}
Or you can check it in https://codepen.io/soorta/pen/gqEGyQ

How to change the Color of the button When click the Checkbox

Here, there is a button and two more check boxes are added. I am trying to do is, when I click on any check box, the Button color should change to green or any other color. If I unchecked all the boxes, the button color should change to gray color. Please help me. Thank you.
.input {
font-weight: bold;
border-radius: 1px;
background-color: grey;
}
<input id="input" class="" value=" ... " type="button">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
Use document.querySelectorAll to select elements
Use .check-box:checked to select checked elements[:checked]
var elems = document.querySelectorAll('.check-box');
var btn = document.querySelector('.btn-elem');
[].forEach.call(elems, function(el) {
el.addEventListener('change', function() {
var checked = document.querySelectorAll('.check-box:checked');
if (checked.length) {
btn.style.backgroundColor = 'green';
} else {
btn.style.backgroundColor = '';
}
});
});
<input class="btn-elem" value=" ... " style="font-weight: bold; border-radius: 1px; background-color: grey;" type="button">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
Here is an example using pure javascript only (no jquery) :
var button = document.getElementById("mybtn");
var chkbox = document.getElementsByClassName("chkbox");
function onChangeListener() {
button.style.backgroundColor = "gray";
for (var i = 0; i < chkbox.length; i++) {
if (chkbox[i].checked) {
button.style.backgroundColor = "green";
}
}
}
for (var i = 0; i < chkbox.length; i++) {
var checkbox = chkbox[i];
checkbox.addEventListener("change", onChangeListener);
}
<input type="button" id="mybtn" value=" . . . " style="background-color: gray;">
<input type="checkbox" class="chkbox">
<input type="checkbox" class="chkbox">
<input type="checkbox" class="chkbox">
Fiddle here : https://jsfiddle.net/avh4dsnm/1/
To elaborate slightly on Rayon's excellent answer and to make this a bit more dynamic. You could use a data attribute to specify the colour for the button to be for example
<input type="checkbox" class="check-box" data-color="green">
<input type="checkbox" class="check-box" data-color="blue">
You would then need another variable for the colour
var colour = checked.dataset.color;
if (checked.length) {
btn.style.backgroundColor = colour;
} else {
btn.style.backgroundColor = '';
}
Just for fun, here's a CSS-only solution:
#input {
font-weight: bold;
border-radius: 1px;
background-color: grey;
float:left;
}
input:checked ~ #input {
background:green;
}
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input type="checkbox" class="check-box">
<input id="input" class="" value=" ... " type="button">
what should be the code if I am using a multiple buttons?
checkbox 1 --> button 1
checkbox 2 --> button 2
var elems = document.querySelectorAll('.check-box');
var btn = document.querySelector('.btn-categ1');
[].forEach.call(elems, function(el) {
el.addEventListener('change', function() {
var checked = document.querySelectorAll('.check-box:checked');
if (checked.length) {
btn.style.backgroundColor = '#A6EBF2';
} else {
btn.style.backgroundColor = '';
}
});
});

Use JQuery To Change Seperate Radio Button State and Run Associated Function

The goal of this code is that when you change the Section Bar radio input to yes two things happen.
JS Fiddle Link
The .bar div is shown
The Section Foo radio button is changed to the No value and the .foo div is hidden
Additionally, would it be possible to have the reverse happen when the Section Bar is changed back to no. The .bar div gets hidden, the .foo section is shown, and the Section Foo button is set back to yes value.
Basically, the state of the second radio button effects the first button and runs the function it would if it was changed, but the first button does not effect the second when it is changed.
<form>
<label>Section Foo</label>
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" checked >Yes
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no">No
</form>
<form>
<label>Section Bar</label>
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="yes">Yes
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="no" checked>No
</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
div {
width: 500px;
height: 200px;
}
.foo {
display: block;
background: red;
}
.bar {
display: none;
background: black;
}
$('.toggle').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
} else {
$(target).slideUp(300);
}
});
$('.enable').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
$( ".toggle" ).prop("checked", true) // this changes the .toggle check, but does not run the function, also I'm not sure if it will always set it to the value of no.
} else {
$(target).slideUp(300);
$( ".toggle" ).prop("checked", true)
}
});
All you need to do is change the value of the other radio group to no when this one is yes and then trigger its change:
$('.toggle').change(function () {
var foov = $(".toggle:checked").val();
var target = $(this).data("target");
if (foov == 'yes') {
$(target).slideDown(300);
$('.enable[value="no"]').prop('checked', true).trigger('change');
} else {
$(target).slideUp(300);
}
});
$('.enable').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
$('.toggle[value="no"]').prop('checked', true).trigger('change');
} else {
$(target).slideUp(300);
}
});
jsfiddle DEMO
If I understand correctly. Then something like this should do the trick.
jQuery(function($){
var fooRadio = $(':input[name=enableFoo]'),
barRadio = $(':input[name=enableBar]');
function hideShow(el, show) {
el = $(el);
if (show) {
el.slideDown(300);
} else {
el.slideUp(300);
}
}
// bindings
fooRadio.on('change', function(){
var it = $(this),
target = it.data('target');
hideShow(target, it.val()==='yes');
});
barRadio.on('change', function(){
var it = $(this),
target = it.data('target'),
active = it.val()==='yes';
hideShow(target, active);
if (active) {
fooRadio.filter('[value=no]').click();
}
});
});
Here's a fiddle if it http://jsfiddle.net/ccn8f84r/1/
Here following is what you want
$('input[type=radio][name=enableFoo]').change(function() {
var target = $(this).data("target")
if ($(".toggle:radio:checked").val() == 'yes') {
$(target).slideDown(300);
$( ".enable" ).prop("checked", true).trigger('change')
} else {
$(target).slideUp(300);
}
});
$('input[type=radio][name=enableBar]').change(function() {
var target = $(this).data("target")
// alert($(".enable:radio:checked").val())
if ($(".enable:radio:checked").val() == 'yes') {
$(target).slideDown(300);
$( ".toggle" ).prop("checked", true).trigger('change')
} else {
$(target).slideUp(300);
}
});
div {
width: 500px;
height: 200px;
}
.foo {
display: block;
background: red;
}
.bar {
display: none;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Section Foo</label>
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" checked >Yes
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no">No
</form>
<form>
<label>Section Bar</label>
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="yes">Yes
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="no" checked>No
</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
Check Fiddle
Little more simplified using if...elseif and i gave id's to your input type=radio
Working : Demo
HTML : Added id's
<form>
<label>Section Foo</label>
<input id="1" class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" />Yes
<input id="2" class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no" />No</form>
<form>
<label>Section Bar</label>
<input id="3" class="enable" data-target=".bar" type="radio" name="enableBar" value="yes" />Yes
<input id ="4" class="enable" data-target=".bar" type="radio" name="enableBar" value="no" />No</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
CSS : No Change
JS
$("input[type=radio]").click(function () {
var curClass = this.className;
var curValue = this.value;
if (curClass == "toggle" && curValue == "yes") {
document.getElementById('4').checked = true;
$(".bar").slideUp(300);
$(".foo").slideDown(300);
}
else if (curClass == "toggle" && curValue == "no") {
document.getElementById('3').checked = true;
$(".foo").slideUp(300);
$(".bar").slideDown(300);
}
else if (curClass == "enable" && curValue == "yes") {
document.getElementById('2').checked = true;
$(".foo").slideUp(300);
$(".bar").slideDown(300);
}
else if (curClass == "enable" && curValue == "no") {
document.getElementById('1').checked = true;
$(".bar").slideUp(300);
$(".foo").slideDown(300);
}
});

Categories

Resources