Checkbox Enable/Disable DIV - Localstorage - Onload load the status - javascript

I use this checkbox type in my index.html :
<input class="check-1" type="checkbox" value="1" id="check-1"/>
This code in my .js
$(".Categorie.1").show();
$(".check-1").click(function() {
if($(this).is(":checked")) {
$(".Categorie.1").hide();
} else {
$(".Categorie.1").show();
}
});
//localstorage
$('input[type="checkbox"]').each(function(){
$(this).prop('checked', (localStorage.getItem($(this).attr('id')) === 'true') ? 'checked' : '')
});
$('input[type="checkbox"]')
.on('change', function() {
localStorage.setItem($(this).attr('id'), this.checked);
if (this.checked) {
$('.' + $(this).data('target')).show();
} else {
$('.' + $(this).data('target')).hide();
}
})
.trigger('change');
When i load the page, no problem, the checkboxes that are checked are still ticked. But the DIV appears...
Is there a solution for resolve this ?
Btw, I think the code is quite heavy. Is it possible to make a more compact version?
Big thanks all :-)

//fake out the localStorage for StackOverflow
var fakeLocalStorage = {
getItem: function ( key ) {
if ( key === 'check-1' ) {
return 'true';
}
return null;
}
};
$('.check-1').on('change', function() {
if (this.checked) {
$(".Categorie.1").hide();
} else {
$(".Categorie.1").show();
}
});
$('input:checkbox').each(function(){
var originalValue = this.checked;
this.checked = fakeLocalStorage.getItem(this.id) === 'true';
// Changing the value of the checked logically does not generate
// an event. If you want to force the change listener to execute
// due to your change, you can logically trigger the event
if (originalValue != this.checked) $(this).trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="check-1" type="checkbox" value="1" id="check-1">
<div class="Categorie 1">Show Me!</div>

Here a more complete code.
The saving process is ok. Refresh, the checkboxes always checked.
But if you check for remove the red or other, after refresh, the DIV are back.
Thanks ;-)
$("input[type=checkbox]").each(function() {
var name = $(this).attr('name');
if (localStorage.getItem(name) == "true") {
$(this).prop('checked', true);
}
});
$("input[type=checkbox]").change(function() {
var name = $(this).attr('name'),
value = $(this).is(':checked');
localStorage.setItem(name, value);
});
$('.togglebox').change(function () {
$("."+this.value).toggleClass('hide');
});
.one {
background: red;
}
.two {
background: green;
}
.three {
background: blue;
}
.four {
background: black;
}
.hide {
display: none;
}
<input class="togglebox" id="one-box" type="checkbox" name="boxes1" value="one" >First
<input class="togglebox" id="two-box" type="checkbox" name="boxes2" value="two" >Second
<input class="togglebox" id="three-box" type="checkbox" name="boxes3" value="three" >Third
<input class="togglebox" id="four-box" type="checkbox" name="boxes4" value="four" >Fourth
<div style="width: 300px; height: 100px;" class="one"></div>
<div style="width: 300px; height: 100px;" class="two"></div>
<div style="width: 300px; height: 100px;" class="three"></div>
<div style="width: 300px; height: 100px;" class="four"></div>

Related

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

How do I check to make sure all my input:radio elements have a value?

I'm working on a form, and I've got a code that works for validating radio fields. However I plan on having many, MANY radio fields and I feel that my current method, which names each radio field individually, to be a bit tedious. I feel there must be a way I can simply select all of them to make sure they've all been checked before processing the form.
Here is my jsFiddle
Current jQuery
$("form").on("keyup change", function(){
food = $(":checked[name=food]");
color = $(":checked[name=color]");
if (food.val() == "" || food.val() == undefined ||
color.val() == "" || color.val() == undefined){
//Do stuff
} else {
//Do other stuff
}
});
jQuery I'm trying
$("form").on("keyup change", function(){
radio_req = $(".required:checked[type=radio]");
if ( radio_req == "" || radio_req == undefined ) {
//Do stuff
} else {
//Do other stuff
}
});
With the 2nd one, I'm trying to see if I can just add a class of required to all my radio fields, and then just see if any .required radio buttons are left unselected/undefined. I feel there has to be a way for this to work. Am I on the right track? I feel like I'm just not selecting this right.
I have updated your fiddle, check it !
I hope it will solve your problem.
You can test the snippet under.
This is the part i modified :
var checker = function(){
var checked = $.unique($(".required:checked[type=radio]").map(function(){
return this.name;
}));
var not_checked = $.unique($(".required:not(:checked)[type=radio]").map(function(){
return this.name;
}));
if (checked.length !== not_checked.length){
$("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
$(".submit").text("* All fields must be completed and contain valid entries before submitting.");
} else {
$("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
$(".submit").text("");
}
};
$("form").on("keyup change", checker);
checker();
$(document).ready(function(){
// for each Question we have 3 choices:
// so when we answer we have 1 checked and 2 unchecked
// we loop over question
// we fill 2 arrays(checked, unchecked)
// with names of radio
// for each question we will have something like that
// Question 1 : food
// checked = ['food']; notchecked = ['food','food']
// we make them unique ! it becomes
// checked = ['food']; notchecked = ['food'];
// we know now that the First question have been answered
// we loop over all question :
// checked = ['food'] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
// we wait for checking !
// let answer Qestion 2
// checked = ['food' , 'color] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
// etc etc . . .
// when checked.length === notchecked.length => we have an answer for all question
var checker = function(){
var checked = $.unique(
$(".required:checked[type=radio]").map(function(){
return this.name;
})
);
var not_checked = $.unique(
$(".required:not(:checked)[type=radio]").map(function(){
return this.name;
})
);
if (checked.length !== not_checked.length){
$("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
$(".submit").text("* All fields must be completed and contain valid entries before submitting.");
} else {
$("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
$(".submit").text("");
}
};
$("form").on("keyup change", checker);
checker();
});
input {
margin: 7px;
}
.valid {
background-color: green;
border: 3px solid darkgreen;
color: white;
}
.invalid {
background-color: grey;
border: 3px solid darkgrey;
color: black;
}
.error {
color: red;
}
#submit {
display: block;
border-radius: 10px 10px 10px 10px;
width: 130px;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<br>Which of the following do you like the most?
<br>
<input type="radio" class="required" name="food" value="pizza">Pizza
<input type="radio" class="required" name="food" value="burgers">Burgers
<input type="radio" class="required" name="food" value="Salads">Salads
<br>
<br>Which of the following colors do you like the most?
<br>
<input type="radio" class="required" name="color" value="red">Red
<input type="radio" class="required" name="color" value="blue">Blue
<input type="radio" class="required" name="color" value="yellow">Yellow
<br>
<br>Which of the following town do you like the most?
<br>
<input type="radio" class="required" name="town" value="red">New York
<input type="radio" class="required" name="town" value="blue">Miami
<input type="radio" class="required" name="town" value="yellow">Las Vegas
<br>
<br>Which of the following country do you like the most?
<br>
<input type="radio" class="required" name="country" value="red">USA
<input type="radio" class="required" name="country" value="blue">Canada
<input type="radio" class="required" name="country" value="yellow">Chili
<br>
<br>Which of the following car do you like the most?
<br>
<input type="radio" class="required" name="car" value="red">Ferrari
<input type="radio" class="required" name="car" value="blue">Dodge
<input type="radio" class="required" name="car" value="yellow">Chevrolet
<br><br>
<input type="submit" id="submit" class="invalid">
<span class="submit error"></span>
</form>
You can iterate through all the radio buttons that have a name attribute :radio[name] in combination with an array, say examined, that helps you skip buttons that have already been checked. This should be work irrespective of how many sets of radio buttons there are in you form.
$('form').on('input change', function(e) {
e.preventDefault();
var all_selected = true;
var examined = [];
$(':radio[name]').each(function() {
if( examined.indexOf( this.name ) === -1 ) {
examined.push( this.name );
if( !$(':radio:checked[name=' + this.name + ']').length ) {
all_selected = false;
return false;
}
}
});
if( all_selected ) {
//DO STUFF
} else {
//DO OTHER STUFF
}
});
$(function() {
$('form').on('input change', function(e) {
e.preventDefault();
var all_selected = true;
var examined = [];
$(':radio[name]').each(function() {
if( examined.indexOf( this.name ) === -1 ) {
examined.push( this.name );
if( !$(':radio:checked[name=' + this.name + ']').length ) {
all_selected = false;
return false;
}
}
});
if( all_selected ) {
//DO STUFF
console.log( 'All parts completed' );
} else {
//DO OTHER STUFF
console.log( 'Form not complete' );
}
});
});
input {
margin: 7px;
}
.valid {
background-color: green;
border: 3px solid darkgreen;
color: white;
}
.invalid {
background-color: grey;
border: 3px solid darkgrey;
color: black;
}
.error {
color: red;
}
#submit {
display: block;
border-radius: 10px 10px 10px 10px;
width: 130px;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Which of the following do you like the most?<br>
<input type="radio" class="required" name="food" value="pizza">Pizza
<input type="radio" class="required" name="food" value="burgers">Burgers
<input type="radio" class="required" name="food" value="Salads">Salads <br><br>
Which of the following colors do you like the most?<br>
<input type="radio" class="required" name="color" value="red">Red
<input type="radio" class="required" name="color" value="blue">Blue
<input type="radio" class="required" name="color" value="yellow">Yellow
<input type="submit" id="submit" class="invalid">
<span class="submit error"></span>
</form>

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);
}
});

How do you get a Radio Button to change text color in html with jquery?

Here is the code I Have cant figure out how to get the value of the radio button to be read by jquery and then into a function that will then change the color of the text.
Code: https://jsfiddle.net/RhnvU/3898/
HTML:
<span id="quotechange"> HEllloooooo </span>
<div id="mydiv">
Color:
<label class="color1"><input type="radio" name="color" value="color1" checked="checked">Black</label>
<label class="color2"><input type="radio" name="color" value="color2" >Purple</label>
<label class="color3"><input type="radio" name="color" value="color3" >Orange</label>
<label class="color4"><input type="radio" name="color" value="color4" >Red</label> <br>
Style:
<label class="stylebold"><input type="checkbox" name="style1" value="stylebold" > Bold</label>
<label class="styleitalic"><input type="checkbox" name="style2" value="styleitalic" > Italic</label>
</div>
CSS:
.color1 {
color: black;
}
.color2 {
color: purple;
}
.color3 {
color: orange;
}
.color4 {
color: red;
}
JS:
$('#mydiv input').click(colorClick($('input[name=color]:checked', '#mydiv').val()));
function colorClick(color) {
if(color == "color1") {
$("#quotechange").removeClass("color2");
$("#quotechange").removeClass("color3");
$("#quotechange").removeClass("color4");
$("#quotechange").addClass("color1");
}
else if(color == "color2"){
$("#quotechange").removeClass("color1");
$("#quotechange").removeClass("color3");
$("#quotechange").removeClass("color4");
$("#quotechange").addClass("color2");
}
else if(color == "color3"){
$("#quotechange").removeClass("color1");
$("#quotechange").removeClass("color2");
$("#quotechange").removeClass("color4");
$("#quotechange").addClass("color3");
}
else if(color == "color4"){
$("#quotechange").removeClass("color1");
$("#quotechange").removeClass("color3");
$("#quotechange").removeClass("color2");
$("#quotechange").addClass("color4");
}
}
You can simple use $(this).val()
$('#mydiv input:radio').on('change', function() {
$('#test').attr('class', '').addClass($(this).val());
});
$('#mydiv input:checkbox').on('change', function() {
$('#test').addClass($(this).val());
//or if you use this, it will take care when unchecked
//$('#test').toggleClass($(this).val());
});
Demo: https://jsfiddle.net/erkaner/RhnvU/3908/
Update
Issue fixed: When bold and/or italic are checked and a new color is picked the bold and italic remain checked but the value gets reset for them
DEMO: https://jsfiddle.net/erkaner/RhnvU/3910/
$('#mydiv input:radio').on('change', function () {
var checkedboxes = $('#mydiv input:checkbox:checked').map(function(){
return $(this).val();
}).get();
$('#test').attr('class', checkedboxes.join(' ')).addClass($(this).val());
});
$('#mydiv input').click(function(){
colorClick($('input[name=color]:checked', '#mydiv').val())
});
The syntax of your click function was wrong except that what you did was right and you could use $(this) instead of $('input[name=color]:checked', '#mydiv')
DEMO Fiddle

Remove input value jquery

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);
}
});

Categories

Resources