add onto checked values in checkbox via jquery - javascript

Hi Im trying to add onto a checkbox's values selected, so maintain the selected values but add other selected values. however the attribute doesn't add selected values. here is my attempt (p.s how would I in turn remove values selected and keep existing values selected?) thanks
$('.add_button').click(function() {
var values = $('input:checkbox:checked.ssremployeeids').map(function () {
return this.value;
}).get();
$('.ssremployeeid').attr('selected',values);
<div class="grs-multi-select-area" style="height:120px;width:150px;">
<div class="grs-multi-select-box ">
<input id="ssrBox" class="ssremployeeid" type="checkbox" name="ssremployeeid[]"
value="1312">
Amanda Becker
</div>
<div class="grs-multi-select-box "> // same as above I just collapsed it for viewing purposes
<div class="grs-multi-select-box ">
<div class="grs-multi-select-box ">
</div> //closes main div
});

I am still not sure if I understood you question correctly, but based one what I understood here's something you could try:
Sample Fiddle: http://jsfiddle.net/HFULf/1/
HTML
<div id="div1">
<input type="checkbox" name="cb1" value="val1" checked="checked" />
<input type="checkbox" name="cb2" value="val2"/>
<input type="checkbox" name="cb3" value="val3"/>
</div>
<div id="div2">
<input type="checkbox" name="cb1" value="val1"/>
<input type="checkbox" name="cb2" value="val2"/>
<input type="checkbox" name="cb3" value="val3"/>
</div>
<button id="btn1">Add Selected</button>
<button id="btn2">Remove Selected</button>
jQuery
//add selected values from first set of check-boxes to the second set
$('#btn1').click(function(e){
$('div#div1 input[type="checkbox"]:checked').each(function(){
$('div#div2 input[type="checkbox"]').eq($(this).index()).prop('checked',true);
});
});
//remove values from second set of check-boxes if selected in first one
$('#btn2').click(function(e){
$('div#div1 input[type="checkbox"]:checked').each(function(){
$('div#div2 input[type="checkbox"]').eq($(this).index()).prop('checked',false);
});
});
Hope, this will help you a little if not solve your problem entirely.

Related

Appending checkboxes labels of a form into a <p> element

I have been trying to do this for a few hours but couldn't succeed. So I decided to ask help here.
So, I have a form:
<form id="ecommerce-form">
<input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
<label for="seopremium" class="lead">SEO premium</label>
<input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
<label for="moyenpaiement" class="lead">Configuration paiements</label>
<input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
<label for="facturation" class="lead">Facturation simplifiée</label>
<input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
<label for="avisclients" class="lead">Avis clients</label>
<input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
<label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
<input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
<label for="basketoptions" class="lead">Panier avec options</label>
</form>
And I'm trying to print the label's text of checkboxes that are checked automatically into a Paragraph:
<p class="recap-option"><strong>Options:</strong></p><p class="options-selected"></p>
So if everything is checked the Paragraph would be:
<p class="recap-option"><strong>Options:</strong></p><p class="options-selected">SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options</p>
Or in clear:
Options: SEO premium, Configuration paiements, facturation simplifiée, Avis clients, Sécurité supplémentaire, Panier avec options
I found a few solutions here for problems that seemed relatively similar but I wasn't able to adapt the code for my own needs.
http://jsfiddle.net/5ryy9krn/2/
So the goal is simply appending what is between each into the paragraph element.
Thanks in advance for any help.
You need to fetch the label element and use its value to append into the selected-area.
And on uncheck, also follow the same procedure to remove the unchecked element from the selected-area
You can define the onChange function in the following way to achieve the expected behavior.
$('input[type="checkbox"]').on('change', function() {
if ($(this).is(':checked')) {
var elements = $(this).parent('div');
const checkedItem = elements.find("label").text();
$('#seleted-rows').append(`<p name="${checkedItem}">${checkedItem}</p>`);
} else {
var elements = $(this).parent('div');
const uncheckedItem = elements.find("label").text();
$('#seleted-rows').find(`p[name="${uncheckedItem}"]`).remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pb-5 devis-invisible" id="devis-ecommerce">
<form id="ecommerce-form">
<div class="row pb-5">
<div class="col-4">
<input type="checkbox" id="seopremium" name="option-ecommerce" value="seopremium">
<label for="seopremium" class="lead">SEO premium</label>
</div>
<div class="col-4">
<input type="checkbox" id="moyenpaiement" name="option-ecommerce" value="moyenpaiement">
<label for="moyenpaiement" class="lead">Configuration paiements</label>
</div>
<div class="col-4">
<input type="checkbox" id="facturation" name="option-ecommerce" value="facturation">
<label for="facturation" class="lead">Facturation simplifiée</label>
</div>
</div>
<div class="row">
<div class="col-4">
<input type="checkbox" id="avisclients" name="option-ecommerce" value="avisclients">
<label for="avisclients" class="lead">Avis clients</label>
</div>
<div class="col-4">
<input type="checkbox" id="additionnalsecurity" name="option-ecommerce" value="additionnalsecurity">
<label for="additionnalsecurity" class="lead">Sécurité supplémentaire</label>
</div>
<div class="col-4">
<input type="checkbox" id="basketoptions" name="option-ecommerce" value="basketoptions">
<label for="basketoptions" class="lead">Panier avec options</label>
</div>
</div>
</form>
</div>
<div>
<p>Selected Items</p>
<div id="seleted-rows">
</div>
</div>
You seem to want something like this:
var labels = document.querySelectorAll("input:checked ~ label);
labels.foreach(function(label) {
console.log(label.textContent);
});
It isn't clear to me which paragraph you want these labels added to, so I used console.log and left it for you to put the label.texContent into your paragraph(s)
You have to gather all input[type=checkbox]:checked and the labels.
Using your example this could be done with:
var nodelistChecked = document.querySelectorAll("#ecommerce-form input[type=checkbox]:checked");
// nodelistChecked now contains a Node-list with all checked input elements
With this result you can gather the text from the labels with an Array.prototype.map function call. The result from a querySelectorAll()-call is a Nodelist and doesn't know forEach/map/or other Array-like function-calls, so you have to call it and convert it with map to an array.
var arrLabelText =
Array.prototype.map.call(nodelistChecked, function(node) {
return (document.querySelector('label[for='+node.id+']')
|| document.createElement('label')).textContent;
});
// arrLabelText contains an array with all selected labels
// the || new element is used, to avoid errors if no label is found
After this you can display the value in the element you want to display it:
document.querySelector("p.options-selected").innerText = arrLabelText.join(', ');
When you use jQuery it is a a bit shorter and it avoids some error-checking (like no label found):
function fillSelectedOptions() {
$("p.options-selected").text(
Array.prototype.slice.call( // depending on the jQuery version, this might be required
$("#ecommerce-form input[type=checkbox]:checked")
.map(function(i,node) { /* jQuery returns the index first */
return $('label[for="'+node.id+'"]').text()
})
).join(', ')
);
}
$("#ecommerce-form input[type=checkbox]").each(function(i, node) {
$(node).on('change', fillSelectedOptions);
});

Can I set a checkbox to be enabled or disabled based on whether multiple checkboxes are checked?

So I have multiple row of check boxes like the picture below
I want to make the add,edit and delete checkbox in the same row be disabled when the most left checkbox in the same row is checked using jquery, i try using solution in here solution, but this solution only work for 1 group of checboxes, i'm gonna have a lot of checkboxes group, i prefer using loop statement for this case, but i cant come up with any solution.
here's my html code:
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="aauth100" value="auth100" id="auth100" onclick ="togAuth1()">New Member + Kit Purchase</input></div>
<div class="col-sm-2"><input type="checkbox" name="aaddAuth100" value="addAuth100" id="addAuth100">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="aeditAuth100" value="editAuth100" id="editAuth100">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="adelAuth100" value="delAuth100" id="delAuth100">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth101" value="auth101" id="auth101">New Member Registration</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth101" value="addAuth101" id="addAuth101">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth101" value="editAuth101" id="editAuth101">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth101" value="delAuth101" id="delAuth101">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth102" value="auth102" id="auth102">Member Data Maintenance</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth102" value="addAuth102" id="addAuth102">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth102" value="editAuth102" id="editAuth102">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth102" value="delAuth102" id="delAuth102">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth103" value="auth103" id="auth103">Member Registration Listing</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth103" value="addAuth103" id="addAuth103">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth103" value="editAuth103" id="editAuth103">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth103" value="delAuth103" id="delAuth103">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth104" value="auth104" id="auth104">Geneology Listing</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth104" value="addAuth104" id="addAuth104">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth104" value="editAuth104" id="editAuth104">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth104" value="delAuth104" id="delAuth104">Delete</input></div>
</div>
<div class="row">
<div class="col-sm-5"><input type="checkbox" name="auth105" value="auth105" id="auth105">Member Rank Report</input></div>
<div class="col-sm-2"><input type="checkbox" name="addAuth105" value="addAuth105" id="addAuth105">Add</input></div>
<div class="col-sm-2"><input type="checkbox" name="editAuth105" value="editAuth105" id="editAuth105">Edit</input></div>
<div class="col-sm-2"><input type="checkbox" name="delAuth105" value="delAuth105" id="delAuth105">Delete</input></div>
</div>
You can assign some class to your checkbox. Then use the .each() method of jquery this way.
$(".someclass").each(function(){
if($(this).is(':checked'))
{
// Disable other checkbox in row
}
else
{
//don't disable checkbox
}
})
This will loop through all the checkbox with the assigned class and you can easily separate the checkbox of left row with class.
Though you will have to find a way, how to target other checkbox at right side in the same row.
One way you can do this is to to use each row. Then from there select the first div and get it's input. That can be used for the change event, which then you can disable all but the first checkbox:
$('.row').each(function(){
var self = this;
$(this).find('div:first input').change(function(){
// disables all but the first input in the div rows
if(this.checked) $(self).find('div:gt(0) input').attr("disabled", true);
else $(self).find('div:gt(0) input').attr("disabled", false);
});
});
Demo
This single line of code does the trick, in a change event:
$('.col-sm-5').on('change', function(){
$(this).nextAll('.col-sm-2').children('input').prop('disabled',
$(this).children('input').prop('checked'));
});
I'll break it down:
$('.col-sm-5').on('change', ...
Whenever an element with the col-sm-5 class (or one of its children) changes...
$(this).nextAll('.col-sm-2') ...
Get all the following siblings of this (the element that changed) which have the class col-sm-2 ...
.children('input') ...
Get the input elements that are children of the above...
.prop('disabled', ...
The disabled property will be set to either true or false ...
$(this).children('input') ...
Get the input box that is contained in the div with the class col-sm-5 that just changed ...
.prop('checked') ...
Find out if it's checked or not. So,
$(this).children('input').prop('checked')
evaluates to either true or false, and we're plugging it into this:
.prop('disabled', [true or false])
So, if the first checkbox is checked, the next three are disabled, and if it isn't, they aren't.

Different way to generate divs via checkbox

Currently I am using the below method using JS to generate a block of text in a right column when a check box is clicked ticked in a left column.
This has been working fine, however each time I need to add a check box, I need to add a new class and new formContainer element. With the original 3 I had, wasn't a big deal. But now that I'm up to 10 and growing, getting a bit cumbersome.
What better possibilities exist to generate a div/block of text on a different part of the page as a result of a ticked check box?
Check Box
<input id="chk" data-detail="<br>Right 1" class="chkbox" type="checkbox" value="results" />1
Creating individual class
<div class="formContainer"></div>
Script
<script>
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
}
else
{
$('.formContainer').html('');
}
});
</script>
If you are wanting them in columns you can generate them using bootstrap gridsystem.
<div class="formContainer>
<div class="container">
<div class="row">
<div class="col-m-4"></div>
<div class="col-m-4"></div>
<div class="col-m-4"></div>
</div>
<div class="row">
...
</div>
</div>
</div>
If you are wanting to keep them in the same column you could just use .append()
$('.formContainer').append('<div class="new">'+$(this).data('detail')+'</div>');
These can be used together to generate a fluid system or just the append can be used to keep adding divs to your formContainer
I would suggest appending a form after your checkbox using the Jquery function .after(newElement);
Play with it on codepen
Html:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<style>
.formContainer{
height: 50px;
width: 100%;
background-color: gray;
}
</style>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
<label class="checkboxLabel">
<input class="checkboxesThatAppends" type="checkbox" value="results" />
Show me a form
</label>
JQuery:
$(document).ready(function(){
$('.checkboxesThatAppends').click(function(){
var associatedFormId = $(this).attr('data-associated-form-id');
if(associatedFormId){
//if there is a form container associated with this checkbox already
//then let's remove that form.
//and remove the association from the checkbox
$('#'+associatedFormId).remove();
$(this).attr('data-associated-form-id', '');
}else{
//generate an Id for the new form to attach.
var newId = new Date().getTime();
$(this).attr('data-associated-form-id', newId);
$(this).parent().after('<div id="'+newId+'" class="formContainer"></div> ');
}
});
});
You can just use jQuery's append() and remove() methods in combination with wrapping HTML elements to achieve this effect.
JSFiddle: https://jsfiddle.net/xuc4tze0/1/
HTML
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 1" class="chkbox" type="checkbox" value="results" />1
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 2" class="chkbox" type="checkbox" value="results" />2
</div>
</div>
<div class="row">
<div class="left">
<input id="chk" data-detail="Right 3" class="chkbox" type="checkbox" value="results" />3
</div>
</div>
CSS
.row {
display: flex;
width: 400px;
}
.left, .right {
flex: 0 0 50%;
}
Javascript / jQuery
$('.chkbox').on('click', function() {
if ($(this).is(':checked'))
// Find the row and add the 'right' column
$(this).closest('.row').append('<div class="right">' + $(this).data('detail') + '</div>');
} else {
// Find the 'right' column and remove it
$(this).closest('.row').find('.right').remove();
}
});
Depending on your need and the content of the divs I got a couple of suggestions :
Modal popups. If you these divs are just notifications then a popup would do (but doubt this is what you need).
List group, use bootstrap's neat class list group to show the needed info in an <ul> element, the JS that comes with these can be neat as well with special animations.
Use tooltips on each checkbox instead of getting a whole div appearing.
Last suggestion which I like least is putting all of your div's in a single container div on the right. Fix its width and height and set overflow attribute so you can scroll up and down the shown divs

Javascript check bootstrap checkbox by id

I have the following form :
<form class="form-inline" role="form">
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox">
<label>
<input type="checkbox" name="discounting" onchange='handleChange(this);' id='check11' > Show only price-discounted products
</label>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="pic-container">
<div class="checkbox" id='check21'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
</div>
</div>
</form>
I'd like to be able to check the second checkbox automatically with JavaScript once I check the first one. I tried using the following script :
<script>
function handleChange(cb) {
if(cb.checked == true) {
alert('Message 1');
document.getElementById("check21").checked = true;
} else {
alert('Message 2');
var x = document.getElementById("check21").disabled= false;
}
}
</script>
But it doesn't work since I think with bootstrap is a question of classes.
The problem as Didier pointed out is that you have two elements with the same ID:
<div class="checkbox" id='check21'>
and
<input type="checkbox" name="discounting" onchange='' id='check21'>
The call to document.getElementById('check21') will probably (because the behavior is undefined) return the first one, which in this case is the <div> element, not the checkbox.
You must not use the same ID on two HTML elements, so you need to change the ID on one or the other of them.
http://jsfiddle.net/uywaxds5/2/
I included boostrap as an external reference.
<div class="checkbox" id='check22'>
<label>
<input type="checkbox" name="discounting" onchange='' id='check21'> Show only price-discounted products
</label>
</div>
Fixing the duplicate id seems to work.
If it does not works, the issue might be in another part of your code.
Use a different name for the second radio button
<input type="checkbox" name="discounting21">
There can only be one selected radio button belonging to the same group(ie. name).

check/uncheck bootstrap checkboxes with jQuery

I've made another post yesterday and had no success with it. I will try now to reorder de idea and to ask again since I can't find the solution for this (I'm a newbie and I'm trying really hard).
The thing is that I'm working with this template based on Bootstrap, and this is the code that I can see directly from one of the files and that I'm using on my project:
html snippet:
<div class="hide" id="states">
<div class="control-group">
<label class="control-label">Seleccione</label>
<div class="controls">
<label class="checkbox span4">
<input type="checkbox" value="all" id="allstates" name="all"/>Todas
</label>
<label class="checkbox span4">
<input class="states" type="checkbox" value="Caba" id="" name="st[]"/>Ciudad Autónoma de Buenos Aires
</label>
<label class="checkbox span4">
<input class="states" type="checkbox" value="Buenos Aires" id="" name="st[]"/> Buenos Aires
</label>
<label class="checkbox span4">
<input class="states" type="checkbox" value="Catamarca" id="" name="st[]"/> Catamarca
</label>
</div>
</div>
</div>
After lot of searching I have founded when inspecting it that my code looks like this (snippet):
<div class="controls">
<label class="checkbox span4">
<div class="checker" id="uniform-allstates">
<span>
<input type="checkbox" value="all" id="allstates" name="all">
</span>
</div>Todas
</label>
<label class="checkbox span4">
<div class="checker">
<span>
<input class="states" type="checkbox" value="Caba" id="" name="st[]">
</span>
</div> Ciudad Autónoma de Buenos Aires
</label>
<label class="checkbox span4">
<div class="checker">
<span>
<input class="states" type="checkbox" value="Buenos Aires" id="" name="st[]">
</span>
</div> Buenos Aires
</label>
<label class="checkbox span4">
<div class="checker">
<span>
<input class="states" type="checkbox" value="Catamarca" id="" name="st[]">
</span>
</div> Catamarca
</label>
</div>
As you can see, another div and another span are added (seriously don't know why or how) so I'm guessing now it's some DOM problem the one I'm having.
This is snippet of my js file:
$('#allstates').click(function() {
$('.checkbox').find('span').addClass('checked');
});
So this function selects ALL the checkboxes I have (even though the ones that I don't want because they belong to another category).
I want to know why the div and span are added and how to select only the checkboxes that I want.
For that I've been trying code like this but no success:
test 1
$('#allstates').click(function() {
if ($(this).is(':checked')) {
$('span input').attr('checked', true);
} else {
$('span input').attr('checked', false);
}
});
test2
$('#allstates').click(function() {
$(".states").prop("checked",$("#allstates").prop("checked"))
});
and so other ones that I erased.
NOTE: No js errors are being displayed when inspecting
Also it is important to add prop to true on selecting checkboxes:
$("#checkAll").click(function(){
var check = $(this).prop('checked');
if(check == true) {
$('.checker').find('span').addClass('checked');
$('.checkbox').prop('checked', true);
} else {
$('.checker').find('span').removeClass('checked');
$('.checkbox').prop('checked', false);
}
});
Since I mentioned that this function checked all the checkboxes I had (even though the ones that were not supposed to be checked), I've been trying to look for the solution:
$('#allstates').click(function() {
$('.checkbox').find('span').addClass('checked');
});
But this is not what I wanted. I mentioned also that I noticed that the code was "different" when inspecting it (in Chrome with F12). So as #thecbuilder said, it changes in order to add style.
I realized that since code is changing... I had to change the class (checkbox) from which I was starting the "span tag" search, so I change class checkbox to id states and this is the result:
$('#allstates').click(function() {
if($(this).attr("checked")){
$('#states').find('span').addClass('checked');
}else{
$('#states').find('span').removeClass('checked');
}
});
Now it finally works.
I think you are looking for code like:
$(document).ready(function()
{
$("#allstates").on("change", function()
{
var checked = $(this).prop("checked");
$(this).parents(".controls")
.first()
.find("input[type=checkbox]")
.prop("checked", checked);
});
});
JsFiddle Example
When the state of the checkbox with the id allstates changes, get the checkbox value, find the first parent html element with a class called controls and then only update all the checkboxes in that element with the value of checked.
Simple bootstrap checkbox
<label><input type="checkbox" value="">Option 1</label>
When debug in Chrome dev tool, label look like
https://tinker.press/images/bootstrap-checkbox-label-2017-01-17_084755.png
To toogle checkbox state just set true|false on lable.control.checked
label.control.checked = false; //uncheck
label.control.checked = true; //check
Video demo https://youtu.be/3qEMFd9bcd8

Categories