label attribute onclick function fired twice - javascript

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

Related

Can you onblur a set of checkboxes?

I have a set of checkboxes, and validation such that at least one of those checkboxes need to be checked on submit. But I want to be able to set a validation error if the user blurs out of the set of checkboxes. The problem is that if I do a blur for the last one it doesn't work because they could be shift-tabbing to the second from last checkbox. I've tried to but the onblur in the fieldset tag, but that didn't trigger a blur at all. Is this just a limitation that can't be overcome with plain html and vanilla JS?
You can look at what the next element that is focused is and determine if they are under the same grouping.
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function (event) {
const nextElem = event.relatedTarget;
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (nextElem?.closest('fieldset') !== fieldSet) {
fieldSet.classList.toggle("error", !isValid);
} else if (isValid) {
fieldSet.classList.remove("error");
}
});
});
.error {
color: red;
}
<form>
<fieldset>
<legend>Pizza One</legend>
<input type="checkbox" name="x1-1" id="x1-1">
<label for="x1-1">Cheese</label>
<input type="checkbox" name="x1-2" id="x1-2">
<label for="x1-2">Peppers</label>
<input type="checkbox" name="x1-3" id="x1-3">
<label for="x1=3">Mushrooms</label>
</fieldset>
<fieldset>
<legend>Pizza Two</legend>
<input type="checkbox" name="x2-1" id="x2-1">
<label for="x2-1">Cheese</label>
<input type="checkbox" name="x2-2" id="x2-2">
<label for="x2-2">Peppers</label>
<input type="checkbox" name="x2-3" id="x2-3">
<label for="x2-3">Mushrooms</label>
</fieldset>
<input type="submit" />
</form>
Adding in a trick to use HTML5 validation
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function(event) {
const nextElem = event.relatedTarget;
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (nextElem?.closest('fieldset') !== fieldSet) {
fieldSet.classList.toggle("error", !isValid);
}
});
elem.addEventListener("change", function(event) {
const fieldSet = elem.closest('fieldset');
const isValid = fieldSet.querySelector("input:checked") !== null;
if (isValid) {
fieldSet.classList.remove("error");
fieldSet.querySelectorAll("input").forEach((cb) => {
cb.removeAttribute("required");
});
} else {
fieldSet.querySelectorAll("input").forEach((cb) => {
cb.setAttribute("required", "required");
});
}
});
const changeEvt = document.createEvent("HTMLEvents");
changeEvt.initEvent("change", false, true);
elem.dispatchEvent(changeEvt);
});
.error {
color: red;
}
<form>
<fieldset>
<legend>Pizza One</legend>
<input type="checkbox" name="x1-1" id="x1-1">
<label for="x1-1">Cheese</label>
<input type="checkbox" name="x1-2" id="x1-2">
<label for="x1-2">Peppers</label>
<input type="checkbox" name="x1-3" id="x1-3">
<label for="x1=3">Mushrooms</label>
</fieldset>
<fieldset>
<legend>Pizza Two</legend>
<input type="checkbox" name="x2-1" id="x2-1">
<label for="x2-1">Cheese</label>
<input type="checkbox" name="x2-2" id="x2-2">
<label for="x2-2">Peppers</label>
<input type="checkbox" name="x2-3" id="x2-3">
<label for="x2-3">Mushrooms</label>
</fieldset>
<input type="submit" />
</form>
Based on epascarello's suggestion I was able to create a function that provided similar functionality to the one provided. I have an error span that's underneath the checkboxes. I wanted behavior that would immediately remove that if any checkbox was checked, but only add the error span if the user blurred out of the entire set of checkboxes. Note that there is only one fieldset on this page, and the error span has an specific id I could reference. Here's the function that I got working:
document.querySelectorAll('input[type="checkbox"]').forEach((elem) => {
elem.addEventListener("blur", function (event) {
var errorSpan = document.getElementById("checkboxesErrorSpan");
var isValid = document.querySelector("fieldset").querySelectorAll("input:checked").length > 0;
if (isValid) {
if ((errorSpan.style.display == "inline")) {
errorSpan.style.display = "none";
}
}
else {
if (event.relatedTarget.type != "checkbox") {
if ((errorSpan.style.display == "none")) {
errorSpan.style.display = "inline";
}
}
}
});
});

Show textfield in other div when radio checked

Alright, I've gone through lot of sources but I've got confused applying them all. I'm new to javascript and jquery.
I have a step by step choices (i got a wizard template). So I wanted to display a text field from the previous step/div when "wedding" radio button is checked.
my html code:
<div id="step-1">
<fieldset>
<input type="radio" id="theme1" name="cake_theme" value="wedding" onchange="see()" />
<input type="radio" id="theme2" name="cake_theme" value="bday" onchange="see()" />
<input type="radio" id="theme3" name="cake_theme" value="occassion" onchange="see()" />
</fieldset>
</div>
<div id="step-2">
Date: <input type="date" name="date_pick"/> //remains
<div class="wed_delivery"> Venue : <input type="text" name="wed_delivery" placeholder="Venue to Delivery"/> //only shows up when "wedding button" is checked
</div>
</div>
<div id="themedisplay" height="100px" width="300px"> </div>
I have in my JS in different file: (working fine)
function see(){
var canvas = document.getElementById('displaycake');
if (document.getElementById('theme1').checked) {
document.getElementById('themedisplay').innerHTML = "Wedding Cake";
}
if (document.getElementById('theme2').checked) {
document.getElementById('themedisplay').innerHTML = "Birthday Cake";
}
if (document.getElementById('theme3').checked) {
document.getElementById('themedisplay').innerHTML = "Occassion Cake";
}
}
I tried putting below the div "step-1"
<script>
$(document).ready(function () {
$(".wed_delivery").hide();
$("#theme1").click(function () { //theme1 is the Wedding Theme
$(".wed_delivery").show();
});
</script>
It doesn't work, is it possible in a Wizard Template?
Thanks in advance, comments each line are appreciated.
This will help you. Point to note.
1: Close your document.ready function properly.
2: Include JQuery if not included.
3: Bind the event with radio buttons and hide/show the text box if the checked radio is/is not wedding radio button
function see(){
var canvas = document.getElementById('displaycake');
if (document.getElementById('theme1').checked) {
document.getElementById('themedisplay').innerHTML = "Wedding Cake";}
if (document.getElementById('theme2').checked) {
document.getElementById('themedisplay').innerHTML = "Birthday Cake";}
if (document.getElementById('theme3').checked) {
document.getElementById('themedisplay').innerHTML = "Occassion Cake";}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="step-1">
<fieldset>
<input type="radio" id="theme1" name="cake_theme" value="wedding" onchange="see()" />
<input type="radio" id="theme2" name="cake_theme" value="bday" onchange="see()" />
<input type="radio" id="theme3" name="cake_theme" value="occassion" onchange="see()" /> </fieldset> </div>
<div id="step-2">
Date: <input type="date" name="date_pick"/> //remains
<div class="wed_delivery"> Venue : <input type="text" name="wed_delivery" placeholder="Venue to Delivery"/> //only shows up when "wedding button" is checked </div>
</div>
<div id="themedisplay" height="100px" width="300px"> </div>
<script>
$(document).ready(function () {
$(".wed_delivery").hide();
$("input[type='radio']").click(function () { //theme1 is the Wedding Theme
if($(this).val() == "wedding")
{
$(".wed_delivery").show();
}
else
{
$(".wed_delivery").hide();
}
});
});
</script>
Establish 2 classes to represent the status of off and on and assign the textbox the .off class initially. When the change event is triggered, then use .addClass() and .removeClass() jQuery methods.
There are too many changes to OP to explain, so I commented details in the Snippet:
SNIPPET
/* Shorthand for $(document).ready(function() { */
$(function() {
/* change event triggered by any radio button */
$(':radio').on('change', function() {
/* $(this) is the function owner,
| in this case it is the specific
| radio button being changed
*/
// Get radio value
var title = $(this).val();
// Get radio data-img
var img = $(this).data('img');
// Get url of background-image
var path = 'http://imgh.us/' + img;
// Set text of figcaption
$('#themeTitle').text(title);
// Set background-image of figure
$('#themeDisplay').css('background', 'url(' + path + ')no-repeat');
// if the checked radio id is 'theme1'...
if ($(this).attr('id') === 'theme1') {
//...status of textbox is on...
$('.wedDelivery').addClass('on').removeClass('off');
} else {
//...otherwise status of textbox is off
$('.wedDelivery').removeClass('on').addClass('off');
}
});
});
.off {
display: none;
}
.on {
display: inline-block;
}
#themeDisplay {
width: 300px;
height: 100px;
}
#themeTitle {
font: 700 16px/1.4 cursive;
color: black;
background: rgba(255, 255, 255, .6);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id='step1'>
<legend>Event Themes</legend>
<!--data-img represents the image file name can be manipulated by .attr() or .data()-->
<label>Wedding
<input type="radio" id="theme1" name="cakeTheme" value="Wedding" data-img='wedcake.jpg'>
</label>
<label>Birthday
<input type="radio" id="theme2" name="cakeTheme" value="Birthday" data-img='bdaycake.jpg'>
</label>
<label>Special Occasion
<input type="radio" id="theme3" name="cakeTheme" value="Special Occasion" data-img='speccake.jpg'>
</label>
</fieldset>
<fieldset id="step2">
<legend>Pick-up/Delivery</legend>
<label>Date:
<input type="date" name="datePick">
</label>
<label class='wedDelivery off'>Venue :
<input type="text" name="wedDelivery" placeholder="Venue to Delivery">
</label>
</fieldset>
<figure id="themeDisplay">
<figcaption id='themeTitle'></figcaption>
</figure>

how to check if a checkbox is checked on page load, and if it does,then show a form?

I am trying to show() a form if the checkbox is checked when the page load. Currently, my checkbox does show that is checked when I refresh the page. But, it doesn't show the form until you click twice, so if you click on the checkbox once it does uncheck it, then click one more time and the checkbox is checked and show the form.
Another issue is that I have 5 checkbox ID and 5 form classes and so I have 5 function doing the same thing. My question is, how can I make one function to work with 5 different ID?
So, there are two question in one:
1)How to display the form is the checkbox is checked
2)How to convert my 5 functions into one function that does show the form depending on the ID passed.
PS: I have
<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="js/setting.js"></script>
inside <head>
Here is the HTML (NOTE: I will post only one div with one ID)
//This is the checkbox
<div class="col-sm-6">
<div class="form-group">
<label class="switch">
<input name="on_off" checked type="checkbox" id="bc1" class="switch-input on-off">
<span class="switch-label" data-on="On" data-off="Off"></span> <span class="switch-handle"></span>
</label>
</div>
</div>
//this is the form
<form class="form-horizontal bc-details1" method="post" action="programs-controller.php" style="display:none" role="form">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" >Start Date:</label>
<div class="input-width input-group date col-sm-10 date-picker">
<input placeholder="MM/DD/YYYY" type="text" style="height:30px; font-size:14px" class="form-control " name="start_date" />
<span class="input-group-addon" ><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</form>
setting.js
$(document).ready(function(){
$('#bc1').change(function () {
if (this.checked) {
$('form.bc-details1').show();
}
else {
$('form.bc-details1').hide();
}
});
$('#bc2').change(function () {
if (this.checked) {
$('form.bc-details2').show();
}
else {
$('form.bc-details2').hide();
}
});
$('#bc3').change(function () {
if (this.checked) {
$('form.bc-details3').show();
}
else {
$('form.bc-details3').hide();
}
});
$('form.bc4').change(function () {
if (this.checked) {
$('form.bc-details4').show();
}
else {
$('form.bc-details4').hide();
}
});
$('#bc5').change(function () {
if (this.checked) {
$('form.bc-details5').show();
}
else {
$('form.bc-details5').hide();
}
});
});
EDIT: my forms are using classes and not ID...However, they have to use different id or class because they have different input and values
Try to call is(':checked') in document ready:
$(document).ready(function() {
if ($('#bc').is(':checked')) {
$('form.bc-details1').show();
} else {
$('form.bc-details1').hide();
}
});
and to have one function for different id use this:
$('input[type=checkbox]').change(function() {
var num = $(this).attr('id').match(/bc([0-9]+)/)[1];
if (this.checked) {
$('form.bc-details' + num).show();
} else {
$('form.bc-details' + num).hide();
}
});
and use same trick for document ready:
$(document).ready(function() {
function check() {
var $checkbox = $(this);
var num = $checkbox.attr('id').match(/bc([0-9]+)/)[1];
if ($checkbox.is(':checked')) {
$('form.bc-details' + num).show();
} else {
$('form.bc-details' + num).hide();
}
}
$('input[type=checkbox]').each(check).change(check);
});

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

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