A variable, Multiple Checkbox Select/Deselect using jQuery - javascript

I found this code to make something have multiple checkbox select/deselect. The code itself works fine but I want it be able to take in a variable so I do not need to write it 20 times in my script.
What it looks like now:
$(function(){
// add multiple select / deselect functionality
$("#selectcase").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectcase").attr("checked", "checked");
} else {
$("#selectcase").removeAttr("checked");
}
});
What I want to take in:
function locatebox(x){
console.log(x);
// add multiple select / deselect functionality
$("#select" + x).click(function(x) {
$("." + x ).attr("checked", this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$("." + x ).click(function(x){
if($("." + x).length == $("." + x + ":checked").length) {
$("#select" + x ).attr("checked", "checked");
} else {
$("#select" + x).removeAttr("checked");
}
});
//locatebox("rase");
}
locatebox("rase");
When I look in the executed code It shows that rase function has been generated but it does not check any boxes.
Thank you to anyone that could possibly help me out.
Edit: I for got to show how I call it and what the check-box values will be.
I do not know if this is the correct to call out the JavaScript.
Call the multi-select check-box:
<td><input type="checkbox" id="selectrase" onclick="locatebox('rase');"/></td>
Defining one check box:
<td align="center"><input type="checkbox" class="rase" name="rase" value="3"/></td>
<td align="center"><input type="checkbox" class="rase" name="rase" value="4"/></td>
Thank you once again.

I think your architecture for this is just fundamentally flawed. Using onclick() and jQuery makes for insanely hard debugging. With jQuery you should be using prop(). Take advantage of classes and the data attribute to target other elements.
Instead consider:
// Wait for the document to load
$(document).ready(function(){
// for all elements that have this class watch for clicks
$('.js-checkbox-group-toggle').on('click', function(){
// create jquery object of what was clicked
var $this = $(this);
// find the selector target for what was clicked;
var target = $this.data('group-target');
// find all the selector targets
var $targets = $(target);
// assign all the targets the value of what was clicked
$targets.prop("checked", $this.prop("checked"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="js-checkbox-group-toggle" data-group-target=".group1" />Targets Group 1<br />
<input type="checkbox" class="js-checkbox-group-toggle" data-group-target=".group2" />Targets Group 2<br />
<input type="checkbox" class="group1" />Hello 1<br />
<input type="checkbox" class="group2" />Hello 2<br />
<input type="checkbox" class="group1" />Test 1<br />
<input type="checkbox" class="group2" />Test 2<br />
<input type="checkbox" class="group2" />English 2<br />
<input type="checkbox" class="group1" />Breakfast 1<br />
Add as MANY of these as you want, you have no variables in JS to mess with and the code base never has to change.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<td><input type="checkbox" id="selectrase" /></td>
<td align="center"><input type="checkbox" class="rase" name="rase" value="3"/></td>
<td align="center"><input type="checkbox" class="rase" name="rase" value="4"/></td>
...
<script type="text/javascript"><!--
function locatebox(x){
console.log(x);
// add multiple select / deselect functionality
var id = "#select" + x;
var className = '.' + x;
$(id).click(function(x) {
$(className).prop("checked", $(id).is(':checked'));
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(className).click(function(){
$(id).prop("checked", ($(className).length == $(className + ":checked").length));
});
}
$(document).ready(function(){
locatebox("rase");
}) ;
//--></script>

Related

Select All Checkbox with Trigger - jquery

On my SelectAll checkbox and click trigger should work for all input - which has on-click event on it.
trigger working on selectall, but uncheck selectall not working. its didnt uncheck all input
<input type="checkbox" id="SelectAll" />
<input class="checkBoxClass" name="pid[]" id="pid_1" value="1" onclick="javascript: total_select(1,0.35,2700.00);" type="checkbox">
<input class="checkBoxClass" name="pid[]" id="pid_2" value="2" onclick="javascript: total_select(2,0.35,2700.00);" type="checkbox">
<input class="checkBoxClass" name="pid[]" id="pid_3" value="3" onclick="javascript: total_select(3,0.35,2700.00);" type="checkbox">
Below what i have did
$(document).ready(function () {
$("#SelectAll").click(function () {
$(".checkBoxClass").attr('checked', $(this).attr('checked'));
$(".checkBoxClass").change(function(){
if (!$(this).attr("checked")){
$("#SelectAll").attr("checked",false);
}
});
});
});
Above Jquery working for select-all / UN-select all checkbox - which works if i remove below trigger
$(document).ready(function () {
$("#SelectAll").click(function(){
$(".checkBoxClass").trigger("click");
$(".checkBoxClass").attr('checked', true); // if i remove this line then selectall for checkbox don't works
});
});
but i need above jquery to trigger - total_select function
function total_select(id,carat,price){
var lenChkBox = $("input[name='pid[]']:checked").length;
if(document.getElementById("pid_"+id).checked==true) {
total_select.s++;
document.getElementById("noofs").innerHTML=total_select.s;
total_select.c +=carat;
var cs = (total_select.c).toFixed(2);
document.getElementById("carat").innerHTML=cs;
total_select.p +=price * carat;
avg_price_per = total_select.p/total_select.c;
var ca = (avg_price_per).toFixed(2);
document.getElementById("price").innerHTML="$"+ca;
} else {
total_select.s--;
document.getElementById("noofs").innerHTML=total_select.s;
total_select.c -=carat;
cs = (total_select.c).toFixed(2);
document.getElementById("carat").innerHTML=cs;
total_select.p -=price * carat;
avg_price_per = total_select.p/total_select.c;
var ca = (avg_price_per).toFixed(2);
document.getElementById("price").innerHTML="$"+ca;
}
i tried many :
$(".checkBoxClass").attr('checked', true).triggerHandler('click');
$(".checkBoxClass").prop('checked', true).triggerHandler('click');
but still not working , it do check all input on 'SelectAll' and trigger total_select function with proper result , but when i do un-select/uncheck on 'SelectAll' none of my input get un-select/uncheck
You can both solve your problem and improve code quality by using unobtrusive event handlers instead of outdated on* event attributes.
Firstly you can assign each .checkBoxClass its own change event handler, which can then read the meta data from some data attributes you place on the elements.
Then the select all logic can be simplified to check/uncheck all those elements, while triggering a change event to execute the handler. As you're using jQuery, here's an example:
$('.checkBoxClass').change(function() {
if (!this.checked)
return;
// place total_select() logic here, and read the parameters from the elements' data()
console.log($(this).data());
});
$('#SelectAll').change(function() {
$('.checkBoxClass').prop('checked', this.checked).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="SelectAll" />
<input class="checkBoxClass" name="pid[]" id="pid_1" value="1" data-a="1" data-b="0.35" data-c="2700.00" type="checkbox">A
<input class="checkBoxClass" name="pid[]" id="pid_2" value="2" data-a="2" data-b="0.35" data-c="2700.00" type="checkbox">B
<input class="checkBoxClass" name="pid[]" id="pid_3" value="3" data-a="3" data-b="0.35" data-c="2700.00" type="checkbox">C
I found answer as below, but still any one have any other best solution let me know , thanks
$(document).ready(function () {
$("#SelectAll").click(function(){
$(".checkBoxClass").trigger("click");
$(".checkBoxClass").attr('checked', true);
$(".checkBoxClass").attr('checked', $(this).attr('checked')); //add this line and working proper - hope will help someone
});
});
I know it's not an active thread but I've jost sold a similar problem and I'd like to come out with the solution :D
With this, only those checkboxes will be checked or unchecked and (thus triggered )what have different checked property from #SelectAll.
$(function () {
$('#SelectAll').click(function () {
$('.checkBoxClass').each(function () {
if ($(this).prop('checked') !== $('#SelectAll').prop('checked')) {
$(this).trigger('click');
}
});
});
});
function total_select(id,carat,price){
alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ALL
<input type="checkbox" id="SelectAll" />
A
<input class="checkBoxClass" name="pid[]" id="pid_1" value="1" onclick="javascript: total_select(1,0.35,2700.00);" type="checkbox">
B
<input class="checkBoxClass" name="pid[]" id="pid_2" value="2" onclick="javascript: total_select(2,0.35,2700.00);" type="checkbox">
C
<input class="checkBoxClass" name="pid[]" id="pid_3" value="3" onclick="javascript: total_select(3,0.35,2700.00);" type="checkbox">
<div id="result">
</div>

copy label text to input

I have tried several ways to achieve this, but somehow nothing works for this.
How can I copy the "label text" of respective Radio Button, which is selected by user into the input field (Result Box) in real time?
HTML -
<ul class="gfield_radio" id="input_4_4">
Radio Buttons:
<br />
<li class="gchoice_4_0">
<input name="input_4" type="radio" value="2" id="choice_4_0" class="radio_s" tabindex="4">
<label for="choice_4_0">Hi</label>
</li>
<li class="gchoice_4_1">
<input name="input_4" type="radio" value="4" id="choice_4_1" class="radio_s" tabindex="5">
<label for="choice_4_1">Hello</label>
</li>
<li class="gchoice_4_2">
<input name="input_4" type="radio" value="3" id="choice_4_2" class="radio_s" tabindex="6">
<label for="choice_4_2">Aloha</label>
</li>
</ul>
<br />
<div class="ginput_container">
Result Box:
<br />
<input name="input_3" id="input_4_3" type="text" value="" class="medium" tabindex="3">
</div>
My attempts:
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
alert(response);
}
// also this:
// if ($("input[type='radio'].radio_s").is(':checked')) {
// var card_type = $("input[type='radio'].radio_s:checked").val();
// alert('card_type');
// }
});
You need to traverse the DOM from the radio which was clicked to find the nearest label element.
$('.radio_s').change(function() {
$('#input_4_3').val($(this).closest('li').find('label').text());
});
Example fiddle
You could also use $(this).next('label') however, that relies on the position of the label element not changing. My first example means the label can be anywhere within the same li as the radio button and it will work.
Try this:
$('.radio_s').click(function() {
$("#input_4_3").val($("input:checked" ).next().text());
});
Demo: http://jsfiddle.net/WQyEw/3/
This is a slightly tricky question to answer well. The structure of your HTML implies that there may be more than one of these structures on the page. So you may have more than one set of radio buttons with a corresponding checkbox.
I have put some working code into a jsFiddle.
I made one change: all the code you had in your question is now in <div class="container">. You would need as many of these as you had groups of radio buttons and checkboxes.
You can then have jQuery code like this:
$('ul.gfield_radio').on('change', 'input[type="radio"]', function () {
var label = $('label[for="' + this.id + '"]');
$(this).closest('.container').find('input.medium').val(label.text());
});
This code is not tied to the id values in this particular bit of HTML, but would work as many times as necessary throughout the page.
Why to depend on third party library when you can achieve it with plain javascript:
<script>
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementsByName('input_4');
for (var i = 0; i < a.length; i++) {
document.getElementsByName('input_4')[i].addEventListener('change', function () {
showValue(this);
}, false);
}
}, false);
function showValue(element) {
alert(element.parentNode.getElementsByTagName('label')[0].innerHTML)
}
</script>

adding check all and uncheck all option using value inside checkbox

I am trying to create a select all, unselect all options like we see in email inboxes for a group of checkboxes. I have added an example for this. The working model that I am trying to get is when a I click on checkbox, it should select and unselect that group with a particular value. Also even if we uncheck any single name form the list, it should uncheck the main "select all" checkbox. I've added a jsfiddle, but it doesnt work properly.
$(document).ready(function(){
$("#selectAll").live("click",function(e){
e.preventDefault();
e.stopImmediatePropagation();
var clickedValue=$(this).attr('class');
clickedValue=clickedValue.replace("select", "");
$("#modalEntity").attr("value", "group"+ clickedValue).attr("checked", true);
});
});
http://jsfiddle.net/EBxSu/
UPDATE (changed live to on & some renaming)
First, you should never have elements with the same ID like this:
<input id="modalEntity" class="entity1" type="checkbox" value="group1" name="India">India
<input id="modalEntity" class="entity2" type="checkbox" value="group1" name="UAE">UAE
I rewrote the jQuery code to this:
$(document).ready(function() {
"use strict";
$("input.select").on("click", function() {
$(this).siblings().find("input.entity").prop("checked", $(this).is(":checked"));
});
$("input.entity").on("click", function() {
var $entityGroup = $(this).siblings().andSelf();
$(this).parent().siblings("input.select").prop("checked", $entityGroup.length === $entityGroup.filter(":checked").length);
});
});
.prop() should only be used on jQuery 1.6 and above.
I also rewrote you HTML a bit, look at the updated jsFiddle here: http://jsfiddle.net/sQVe/EBxSu/8/
Just comment if I missed something, but I think this is what you're after.
I updated your code a bit removing multiple IDs and handling the various scenario requested (clearing the select all check box if user selects a child). Also updated your jQuery using .on() rather than .live().
jQuery looks like:
$(function(){
$('.selectAll').on('click', function(evt){
var group = $(this).attr('data-group'),
isChecked = !!($(this).prop('checked'));
$('input[value="' + group + '"]').prop('checked', isChecked);
})
$('.entity').on('click', function(evt){
var group = $(this).attr('value'),
siblings = $('input[value="' + group + '"]'),
isChecked = true;
siblings.each(function(idx, el){
if(!$(el).prop('checked')) {
isChecked = false;
return;
}
})
$('.selectAll[data-group="' + group + '"]').prop('checked', isChecked);
})
})
And the updated HTML:
<ul>
<li>
Country
<ul>
<input type="checkbox" class="selectAll" data-group="group1">Select/Deselect All Country
<li>
<input class="entity" type="checkbox" value="group1" name="India">India
<input class="entity" type="checkbox" value="group1" name="UAE">UAE
...
</ul>
</li>
</ul>
Here's the fiddle:
http://jsfiddle.net/nBh4L/2/
Thanks!
Jack
I have done that for countries only. Html:
<ul>
<li>
Country
<ul>
<input type="checkbox" id="selectAll" class="select1">Select/Deselect All Country
<li>
<input class="entity1 countries" type="checkbox" value="group1" name="India">India
<input class="entity2 countries" type="checkbox" value="group1" name="UAE">UAE
</li>
</ul>
</li>
<li>​
JavaScript:
$(document).ready(function(){
$("#selectAll").click(function(){
if(!$('.countries').attr('checked'))
$('.countries').attr('checked','checked');
else
$('.countries').removeAttr('checked');
});
$('.countries').click(function(){
var allChecked = true;
$('.countries').each(function(index, element){
if(!$(element).attr('checked'))
allChecked = false;
});
if(!allChecked)
$("#selectAll").removeAttr('checked');
else
$("#selectAll").attr('checked','checked');
});
});​
I updated your JS fiddle with a more correct soltuion:
http://jsfiddle.net/EBxSu/2/
There are a few things that I would like you point out that you are doing wrong, and maybe it will help you with this:
You were using HTML "id" and class" attributes wrong. ID should be unique. Class need not be unique - I switched them around for you.
You don't need to prevent default unless you don't want the checkbox to be checked.
You had a with text inside a tag - this is not valid. Only can exist within a tag - so I moved it out side of the
jQuery should not be complicated. It can be very simple. I moved the HTML around a bit (check the link).
Your javascript code is now simply:
$(document).ready(function() {
$(".selectAll").click(function(e) {
$(this).siblings('ul').find('input').attr('checked', $(this).is(":checked"));
});
});​
ID's are meant to be unique per page, but ignoring some of the mark-up problems with your code, I have edited it so it works as you intended. http://jsfiddle.net/xYWWM/5/
$(document).ready(function() {
$("#selectAll").live("click", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var clickedValue = $(this).attr('class');
clickedValue = clickedValue.replace("select", "");
var checkboxes = $("#modalEntity[value=\"group" + clickedValue + "\"]");
checkboxes.attr("checked", !checkboxes.attr("checked"));
});
});
Follow this Tutorial
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
Also, Check out this Fiddle for Demo
Here is the HTML used in the Demo,
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
<td>Droid X</td>
<td>4.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
<td>HTC Desire</td>
<td>3/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
<td>Apple iPhone 4</td>
<td>5/5</td>
</tr>
</table>
Here is the jQuery for the Demo
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
I didn't understand you solution, but here's one. First, keep similar groups of buttons with a common attribute, say relation, having a value of child. Then keep the selector/deselector for that group with the same name but the value of relation attribute set to parent. Now you have to
1.Toggle the state of all similar child checkboxes when the mother's state is toggled:
$("[relation=parent]").change(function() {
name = $(this).prop('name');
$("[relation=child][name="+name+"]").attr('checked',$(this).attr('checked'));
});
2.Toggle the mother's state accordingly when a child's state is toggled:
$("[relation=parent]").change(function() {
name = $(this).attr('name');
$("[relation=child][name="+name+"]").attr('checked',$(this).attr('checked'));
});
$("[relation=child]").change(function() {
name = $(this).attr('name');
if ($(this).attr('checked') == false) {
$("[relation=parent][name="+name+"]").attr('checked',false);
}
else {
if ($("[name="+name+"][relation=child]:checked").length == $("[name="+name+"][relation=child]").length) {
$("[name="+name+"][relation=parent]").attr('checked','true');
}
}
});
There are couple of things you should note while write you code.
1. Keep it simple.
2. Do not use id multiple times
3. Write a html code. Nesting <ul><inputl><li> is not a good idea.
This is simplified solution, which hopefully you'll be able to understand and will be able to implement in later at different situation.
HTML:
<input type="checkbox" id="btn-select-all-1">Select/un-select All
<ul>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
<li><input type="checkbox" class="select1">item1</li>
</ul>
Jquery:
$(document).ready(function(){
var btnSelectAll = $("#btn-select-all-1");
var toSelect = $('.select1')
//monitor the select_all checkbox for changes
//and take appropriate action
btnSelectAll.on('click', function(){
if(btnSelectAll.is(":checked")){
toSelect.attr("checked", "checked");
}else{
toSelect.removeAttr("checked");
}
});
});
jsFiddle: http://jsfiddle.net/U8aFU/
more help and links:
Check if checkbox is checked with jQuery
Setting "checked" for a checkbox with jQuery?
I've modified your HTML slightly since you used same ID twice ...Below is the working script...
<ul><li>
Country
<ul>
<input type="checkbox" id="selectAll1" class="selectAll">Select/Deselect All Country
<li>
<input id="modalEntity1" class="entity" type="checkbox" value="group1" name="India">India
<input id="modalEntity2" class="entity" type="checkbox" value="group1" name="UAE">UAE
</li>
</ul>
</li>
<li>Company<ul>
<input type="checkbox" id="selectAll2" class='selectAll'>Select/Deselect All Company</a>
<li>
<input id="modalEntity3" class="entity" type="checkbox" value="group2" name="Apple">Apple
<input id="modalEntity4" class="entity" type="checkbox" value="group2" name="Google">Google
</li>
</ul>
</li>
</ul>​
jQuery:
$(document).ready(function(){
$('.selectAll').click(function(){
var thisStatus = $(this).attr('checked');
if(thisStatus=='checked'){
$(this).parent('ul').find('input[type="checkbox"]').attr('checked','checked');
}
else{
$(this).parent('ul').find('input[type="checkbox"]').attr('checked',false);
}
});
$('input.entity').click(function(){
var thisStatus = $(this).attr('checked');
if(thisStatus!=='checked'){
$(this).parent().parent('ul').find('input.selectAll').attr('checked',false);
}
else{
$("input.entity:checked").each(function(){
$(this).parent().parent('ul').find('input.selectAll').attr('checked','checked');
});
}
});
});​

Multiple checkbox value will show in textbox

Here is my code :
<body>
<div align="center">
<b>A<input type="checkbox" name="a" id="check" value="a"></b>
<b>B<input type="checkbox" name="b" id="check" value="a"></b>
<b>B<input type="checkbox" name="c" id="check" value="c"></b>
<b>D<input type="checkbox" name="d" id="check" value="d"></b>
</div>
<table align="center">
<tr>
<td>Text:</td>
<td><input type="text" name="text" id="text"></td>
</tr>
</table>
</body>
I'm trying that: if (more than one) checkbox is selected (or checked) that value will be assigned into the checkbox like "abcd" or "acd" or "bd".For that I have written jQuery
<script type="text/javascript">
$(document).click(function(){
if($("#check").attr('checked')){
$("#text").val(("#check").val());
}
});
</script>
able to print one txtbox value at a time,but not able to put all checked value in the textbox at a time.
Where I am going wrong ??Any inputs will appreciated.
I may have not understood you correctly, but does this fiddle help you? http://jsfiddle.net/XwGJ9/1/
The change is the javascript:
var $textInput = $('#text');
var $checkBox = $('#checkboxes');
$('input').click(function(){
populateTextInput();
});
function populateTextInput () {
// empty text input
$textInput.val('');
// print out all checked inputs
$checkBox.find('input:checked').each(function() {
$textInput.val( $textInput.val() + $(this).val() );
});
}
Edit: updated
Use this code
$('.check').click(function(){
$("#text").val('');
$(".check").each(function(){
if($(this).prop('checked')){
$("#text").val($("#text").val()+$(this).val());
}
});
});​
​
With this HTML (use class instead of id for abcd)
<div align="center">
<b>A<input type="checkbox" name="a" class="check" value="a"></b>
<b>B<input type="checkbox" name="b" class="check" value="b"></b>
<b>B<input type="checkbox" name="c" class="check" value="c"></b>
<b>D<input type="checkbox" name="d" class="check" value="d"></b>
</div>
<table align="center">
<tr>
<td>Text:</td>
<td><input type="text" name="text" id="text"></td>
</tr>
</table>​
Also I encourage to use CSS instead of align="center"
See live, running demo
So I think you're wanting to append the values together in the textbox. In that case, do:
<script type="text/javascript">
$(document).click(function(){
if($("#check").attr('checked')){
var textBoxVal = $("#text").val()+$("#check").val(); // Concatenate the existing textbox value with the checkbox value.
// Load the resulting value into new var textBoxVal.
$("#text").val(textBoxVal); // Load the new value into the textbox.
}
});
</script>
I used native JS just to make it clearer what I'm doing.
had used something like this.. might help you
var checkeditems = $('input:checkbox[name="check[]"]:checked')
.map(function() {
return $(this).val()
})
.get()
.join(",");
$("#text").val(checkeditems);
If you just want no multiples of a,b,c,d at one time, the onclick is per checkbox
var boxes = $("input:checkbox");
boxes.each(function(idx,elem){
elem.onclick=function(event){
var choices = "";
boxes.each(function(idx,elem){
choices += elem.checked ? elem.name:"";
});
$('#text').val(choices);
}
});

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});​
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.

Categories