Remove input value jquery - javascript

each time I click on a option his data-type should appear in the input.
But I want if the value is already in the .val of the input should not appear anymore and if I click twice I want to remove the data-type from input.
Here is my Jsfiddle:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial + ',' + type);
}
});
http://jsfiddle.net/xbwocrf3/
Thanks!

One solution is using jquery map:
$('.checkbox').on('click', function() {
$(this).toggleClass('checked');
//save the values of checked in an array
var answerValues = $(".checkbox.checked").map(function() {
return $(this).data("type");
}).get();
//update input text with this values
$(".answer").val(answerValues);
});
.checkbox.checked {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>

Do another check before adding the value there:
$('.checkbox').on('click', function () {
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if (answer.val().length === 0) {
answer.val(type);
} else if (!new RegExp("\,?" + type + "\,?").test(initial)) {
answer.val(initial + ',' + type);
}
});
.checkbox.checked {
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>

Use jQuery's map function to get the type data from all elements. Then combine using the join function.
http://jsfiddle.net/xbwocrf3/8/
$('.checkbox').on('click', function() {
var answer = $('.answer');
$(this).toggleClass('checked');
answer.val( $(".checkbox.checked").map(function() {return $(this).data("type")}).get().join(", ") );
});

This solution is a little cleaner:
http://jsfiddle.net/xbwocrf3/9/ (link updated, I pasted it wrong before)
It uses native checkboxes
Instead of doing something as hard as trying to remove old values, it rewrites the whole value of the input from scratch
The items appear always in their natural order
HTML
<input type="text" class="answer" />
<div>
<input type="checkbox" value="1" name="something" id="something1"/>
<label for="something1">Option #1</label>
</div>
<div>
<input type="checkbox" value="2" name="something" id="something2"/>
<label for="something2">Option #2</label>
</div>
<div>
<input type="checkbox" value="3" name="something" id="something3"/>
<label for="something3">Option #3</label>
</div>
<div>
<input type="checkbox" value="4" name="something" id="something4"/>
<label for="something4">Option #4</label>
</div>
CSS
input[type="checkbox"]{
display: none;
}
input[type="checkbox"]:checked + label{
border:2px solid green;
}
Javascript
$('input[type=checkbox]').on('change', function() {
var $answer = $(".answer");
var checked_values = $.map($("input:checked"), function (element){
return element.value;
});
$answer.val(checked_values);
});

please check fiddle
$('.checkbox').on('click', function () {
$(this).toggleClass('checked');
var typen = '';
$(".checkbox").each(function () {
var type = $(this).data('type');
if ($(this).hasClass('checkbox checked')) {
typen = typen + ',' + type;
}
});
if (typen.length > 0) {
typen = typen.substring(1, typen.length);
}
$('.answer').val(typen);
});

Check if the input has checked class:
if($(this).hasClass('checked'))
return;
Final:
$('.checkbox').on('click', function() {
if($(this).hasClass('checked'))
return;//Stop the execution of the function
var type = $(this).data('type'),
answer = $('.answer'),
initial = $('.answer').val();
$(this).toggleClass('checked');
if(answer.val().length === 0) {
answer.val(type);
} else {
answer.val(initial +','+ type);
}
});

Related

How do I dynamically get the value of an element from an array of elements?

I have a form with 3 checkboxes. I'm trying to the value of whichever checkbox is clicked on. I'm able to get the value of a hardcoded checkbox index (checkbox[0] for example), but I can't get the value of checkbox[i] with vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var inputByIndex = checkboxes[0].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work.
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
Fiddle
You can use event.currentTarget to access the element on which event has occurred.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM.
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function(event) {
var inputByIndex = event.currentTarget.value;
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
In the for loop, use let instead of var to make it work:
document.addEventListener("DOMContentLoaded", function() {
var checkboxes = document.getElementsByClassName('checkbox');
var listType = document.getElementById('ListType');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var inputByIndex = checkboxes[i].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work.
listType.classList.add(inputByIndex);
var spanType = document.getElementById("type");
spanType.innerText = inputByIndex;
});
}
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
the checkboxes list doesn't exist within the closure of the onclick funcion. Instead use this.value.
JS fiddle
Delegate
You need to think of the CSS for more than one listType color or use a set of radio buttons
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('ListTypes').addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === 'checkbox') {
const values = [...tgt.form.querySelectorAll("[type=checkbox]:checked")].map(chk => chk.value);
document.getElementById("type").textContent = values.join(", ")
document.getElementById("ListType").classList.add(...values);
}
});
});
input {
margin: 20px;
}
#ListType.basiclist {
color: red;
}
#ListType.accordionlist {
color: blue;
}
#ListType.internalonly {
color: pink;
}
<form id="ListTypes">
<label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label>
<label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label>
<label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label>
</form>
<div id="ListType">
List Type: <span id="type"></span>
</div>
You just need to select them all using the method you would like (I used querySelectorAll & ) and do an iteration over them (I used forEach()).
This is the most simple function you can ever find.
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(singleCheckbox => {
singleCheckbox.addEventListener('click', () => alert(singleCheckbox.id))
});
<label for="first">First<input type="checkbox" id="first"/></label>
<label for="second">Second<input type="checkbox" id="second"/></label>
<label for="third">Third<input type="checkbox" id="third"/></label>
Just to make clear what was actually the problem with your code...
At the time you click handler will be fired the for loop will end its work and thus, the value of i will become exactly checkboxes.length, and of course, there is no checkbox with such an index, because the last of them has index (checkboxes.length - 1). So the reason is that the code inside of the handler is executed after for loop ends its work.
The solutions were already provided by other users.

label attribute onclick function fired twice

I use onclick attribute in label tag when i put input tag with type checkbox inside label it fire twice but once i changed the type to radio it works fine.
Here is my code
function checkUncheck(el) {
var input = $(el).find("input");
console.log(input);
alert("TESt");
// console.log("input:", input);
// console.log('$(input).parent("div").hasClass("opacity")', $(input).closest("div.config-box").hasClass("opacity"));
var isClickable = $(input).closest("div.config-box").hasClass("opacity");
if (isClickable != true) {
if (input.attr("type") == "radio") {
$(el).closest(".form-group").find("input[name='" + input.attr("name") + "']").closest(".img-check").removeClass("check").find('input').prop('checked', false);
$(el).addClass('check').find('input').prop('checked', true).change();
} else {
if ($(el).hasClass("check")) {
$(el).removeClass("check").find("input").prop("checked", false);
} else {
// alert("TEST");
// el.classList.add("check");
$(el).addClass("check").find("input").prop("checked", true);
console.log($(el));
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="img-check" onclick="checkUncheck(this)">
<div class="bg-img" style="background-image: url('http://www.fujifilm.com.my/Products/digital_cameras/x/fujifilm_x20/sample_images/img/index/ff_x20_008.JPG'); width: 20%;height: 200px;background-position: center;background-size: cover;"></div>
<input type="checkbox" name="chassis" value="valasdfas1" style="visibility:hidden" class="hidden" autocomplete="off">
</label>
Please see the example code here https://codepen.io/abdulqadir88/pen/WKjdEj
Here is the updated code Just added for attribute in the label and connected it with chassis That did the trick.
function checkUncheck(el) {
var input = $(el).find("input");
console.log(input);
alert("TESt");
// console.log("input:", input);
// console.log('$(input).parent("div").hasClass("opacity")', $(input).closest("div.config-box").hasClass("opacity"));
var isClickable = $(input).closest("div.config-box").hasClass("opacity");
if (isClickable != true) {
if (input.attr("type") == "radio") {
$(el).closest(".form-group").find("input[name='" + input.attr("name") + "']").closest(".img-check").removeClass("check").find('input').prop('checked', false);
$(el).addClass('check').find('input').prop('checked', true).change();
} else {
if ($(el).hasClass("check")) {
$(el).removeClass("check").find("input").prop("checked", false);
} else {
// alert("TEST");
// el.classList.add("check");
$(el).addClass("check").find("input").prop("checked", true);
console.log($(el));
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="img-check" for="chassis" onclick="checkUncheck(this)">
<div class="bg-img" style="background-image: url('http://www.fujifilm.com.my/Products/digital_cameras/x/fujifilm_x20/sample_images/img/index/ff_x20_008.JPG'); width: 20%;height: 200px;background-position: center;background-size: cover;"></div>
<input type="checkbox" name="chassis" value="valasdfas1" style="visibility:hidden" class="hidden" autocomplete="off">
</label>
Here is the working solution https://codepen.io/abdulqadir88/pen/QBvaYQ
If you want to use type checkbox i whould prefer to add onclick event to the input element. Like this:
<input type="checkbox" name="chassis" value="valasdfas1" style="visibility:hidden" class="hidden" autocomplete="off" onclick="checkUncheck(this)">
But if you dont need checkbox input type yu can use hidden type like this:
<label class="img-check" onclick="checkUncheck(this)">
<div class="bg-img" style="background-image: url('http://www.fujifilm.com.my/Products/digital_cameras/x/fujifilm_x20/sample_images/img/index/ff_x20_008.JPG'); width: 20%;height: 200px;background-position: center;background-size: cover;"></div>
<input type="hidden" name="chassis" value="valasdfas1" class="hidden" autocomplete="off" >
</label>
You can find both solution here:
https://codepen.io/kovtib/pen/VBbrgq?editors=1111

jquery add / remove item from array

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>

How to get checked checkbox inside in div using jquery?

I have list of checkbox inside a div few are checked. i want to change background color green of div when if checkbox is checked.
And On non checked checkbox background color should be gray.
HTML Code :
<div class="row">
<label>
<div class="col s3" style="padding:10px" id="div39">
<div>
<input type="checkbox" name="chk39" value="39" checked="">
<span>Featured Project</span>
</div>
</div>
</label>
<label>
<div class="col s3" style="padding:10px" id="div40">
<div>
<input type="checkbox" name="chk40" value="40">
<span>Specials/Discounts</span>
</div>
</div>
</label>
</div>
Jquery Code:
var check = 1;
$('div').find('input[type=checkbox]').click(function(event) {
var val = $(this).val();
if(check==1)
{
$('#div'+val).css({'background-color': 'lightgreen'});
check=0;
}else{
$('#div'+val).css({'background-color': 'lightgray'});
check=1;
}
});
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox] :checked').each(function() {
alert('asd');
selected.push($(this).attr('value'));
});
});
Use .closest to find the closest element having specified selector.
Use .change listener over check-box elements than click
Use .change() to invoke change-handler initially.
Also consider Number(this.checked), It will be 0 if this.checked ==> false or otherwise.
$('div').find('input[type=checkbox]').change(function(event) {
var color = ['lightgreen', 'lightgray'];
var index = Number(this.checked);
$(this).closest('.s3').css({
'background-color': color[index]
});
}).change();
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox] :checked').each(function() {
selected.push($(this).attr('value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="row">
<label>
<div class="col s3" style="padding:10px" id="div39">
<div>
<input type="checkbox" name="chk39" value="39" checked="">
<span>Featured Project</span>
</div>
</div>
</label>
<label>
<div class="col s3" style="padding:10px" id="div40">
<div>
<input type="checkbox" name="chk40" value="40">
<span>Specials/Discounts</span>
</div>
</div>
</label>
</div>
you can find the parent div using the closest() method.
$('div').find('input[type=checkbox]').click(function(event) {
var val = $(this).val();
var parent = $(this).closest(".col");
if(this.checked) {
parent.css({
'background-color': 'lightgreen'
});
} else {
parent.css({
'background-color': 'lightgray'
});
}
});
Fiddle
$('div').find('input[type=checkbox]').click(function(event) {
if($(this).is(':checked'))
{
$(this).closest('div').css({'background-color': 'lightgreen'});
}
else
{
$(this).closest('div').css({'background-color': 'lightgray'});
}
});
$(document).ready(function($) {
var selected = [];
$('input[type=checkbox]').not(':checked').closest('div').css({'background-color': 'lightgray'});
$('input[type=checkbox]:checked').closest('div').css({'background-color': 'lightgreen'});
});
Below is the updated fiddle
https://jsfiddle.net/cc3q2axr/
This is how I would do it:
$("input[type='checkbox']").click(function() {
if ($(this).prop("checked") === true) {
$(this).closest(".col").css("background-color", "#36ac3b");
} else {
$(this).closest(".col").css("background-color", "#999");
}
});
Here is the JSFiddle demo

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