Multiple checkbox value will show in textbox - javascript

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

Related

A variable, Multiple Checkbox Select/Deselect using jQuery

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>

radio button in html

I am trying to get the selected value from the radio button this is the jsfiddle.
HTML :
<table>
<tr>
<td> Is Reference Number Available</td>
<td> <input type="radio" name="group1" value="yes" onchange="isReferenceNumberAvailable()"> Yes</input>
<input type="radio" name="group1" value="no" onchange="isReferenceNumberAvailable()"> No </input>
</td>
</tr>
</table>
javascript :
function isReferenceNumberAvailable()
{
var test = document.getElementsByName("group1");
for(var elem in test)
{
if(test[elem].checked)
{
alert(test[elem].value); // got the element which is checked
if(test[elem].value=="yes")
alert("Need to create Reference select box");
else if(test[elem].value=="no")
alert("don't create ");
}
}
}
But when I select the radio button i get the following :
Uncaught ReferenceError: isReferenceNumberAvailable is not defined
Check out this
http://jsfiddle.net/9JQU6/
function isReferenceNumberAvailable()
{
var test = document.getElementsByName("group1");
for(var elem in test)
{
if(test[elem].checked)
{
alert(test[elem].value); // got the element which is checked
if(test[elem].value=="yes")
alert("Need to create Reference select box");
else if(test[elem].value=="no")
alert("don't create ");
}
}
}
Reason
Your code is working only error is javascript place error see this demo
The problem is only that its not getting linked in fiddle, it works when placed inside script tags within your HTML see Check this
<script> Within this together with html its fine </script>
Use following script using jquery
$(document).ready(function(){
$('input:radio').click(function(){
alert$('input[name=group1]:checked').val()); // get selected radio button value
// do what you need here
});
});
http://jsbin.com/anAyIWUN/1/edit
Try always to put all your JS before the closing </body> tag.
Regarding your HTML and scripts I would go with something nicer and simpler:
<table>
<tr>
<td> Is Reference Number Available</td>
<td>
<input type="radio" name="group1" value="yes"> Yes
<input type="radio" name="group1" value="no"> No
</td>
</tr>
</table>
JS:
var $el = document.getElementsByName("group1"),
msg = {"yes":"Need to create Reference select box", "no":"Don't create"};
function getVal(){
if(this.checked) alert( msg[this.value] );
}
for(var i=0; i<$el.length; i++)
$el[i].onchange = getVal;

jQuery - checkboxes selecting all on a row or with similar names & ID's

Using jQuery 1.9.1 & getting XML returned from a query that needs to be displayed in a web page as shown in the picture below. I had asked a similar question several days ago but was all over the place in what I was asking. Hope to ask better questions this time.
For the items in the picture, the XML input would be:
<Classrooms>
<Room Number="3">
<Machine>310</Machine>
<Machine>320</Machine>
<Machine>340</Machine>
<Machine>350</Machine>
</Room>
<Room Number="8">
<Machine>810</Machine>
<Machine>820</Machine>
<Machine>840</Machine>
</Room>
<Room Number="10">
<Machine>1010</Machine>
<Machine>1020</Machine>
</Room>
</Classrooms>
The code below is a function that is called upon a successful AJAX GET and builds the checkboxes in a table on the web page.
var $roomList = $( items );
var roomListString = jQ_xmlDocToString( $roomList );
var roomListXML = $.parseXML(roomListString);
$(roomListXML).find("Row").each(function() {
var activeRooms = $( roomListXML ).find("Row").text();
var nbrRooms = $(activeRooms).find("Room").size();
$(activeRooms).find("Room").each(function() {
var roomNo = $(this).attr("Number");
var roomchk = "Room"+roomNo;
var $tr = $("<tr />");
$tr.append('<td><input type="checkbox" name="'+roomchk+'" id="'+roomchk+'" class="checkall" /><label for="'+roomchk+'">Room '+roomNo+'</td>');
$("#mytable").append( $tr );
$(this).children().each(function() {
var machID = $(this).text();
var idname = "Room"+roomNo+"Mach"+machID;
$tr.append('<td><input type="checkbox" name="'+idname+'" id="'+idname+'" /><label for="'+idname+'">'+machID+'</td>');
$("#mytable").append( $tr );
});
});
});
When the above code is run on the data, the HTML in the table is as shown below.
<tbody>
<tr>
<td>
<input name="Room3" id="Room3" class="checkall" type="checkbox" />
<label for="Room3">Room 3</label>
</td>
<td>
<input name="Room3Mach310" id="Room3Mach310" type="checkbox" />
<label for="Room3Mach310">310</label>
</td>
<td>
<input name="Room3Mach320" id="Room3Mach320" type="checkbox" />
<label for="Room3Mach320">320</label>
</td>
<td>
<input name="Room3Mach340" id="Room3Mach340" type="checkbox" />
<label for="Room3Mach340">340</label>
</td>
<td>
<input name="Room3Mach350" id="Room3Mach350" type="checkbox" />
<label for="Room3Mach350">350</label>
</td>
</tr>
<tr>
<td>
<input name="Room8" id="Room8" class="checkall" type="checkbox" />
<label for="Room8">Room 8</label>
</td>
<td>
<input name="Room8Mach810" id="Room8Mach810" type="checkbox" />
<label for="Room8Mach810">810</label>
</td>
<td>
<input name="Room8Mach820" id="Room8Mach820" type="checkbox" />
<label for="Room8Mach820">820</label>
</td>
<td>
<input name="Room8Mach840" id="Room8Mach840" type="checkbox" />
<label for="Room8Mach840">840</label>
</td>
</tr>
<tr>
<td>
<input name="Room10" id="Room10" class="checkall" type="checkbox" />
<label for="Room10">Room 10</label>
</td>
<td>
<input name="Room10Mach1010" id="Room10Mach1010" type="checkbox" />
<label for="Room10Mach1010">1010</label>
</td>
<td>
<input name="Room10Mach1020" id="Room10Mach1020" type="checkbox" />
<label for="Room10Mach1020">1020</label>
</td>
</tr>
</tbody>
Selection of any checkbox on the page will enable a SUBMIT button on the page, which when clicked will pass the value of the boxes checked into another function. The user can select any number of the individual boxes (the ones with the number beside them), regardless of the room those items are associated with. When the user selects a Room checkbox though, ALL the individual checkboxes for that room should also be checked. The individual values are the ones I want. When the SUBMIT button is clicked, the individual values are all that will be sent to that function.
I had looked at this topic about using a checkbox class to select all.
I'm using the code below to find what's checked. I can see when I select an individual box that it gets added to the array. I can also see when I select a Room that the checkall is found, but I can't seem to make the individual checkboxes get checked once I do. I had been attempting to use the Attribute Starts With jQuery selector, but haven't been able to get it to check the boxes.
$("#mytable").click(function(e) {
var ele = $(this).find(":checkbox");
var zall = $(this).find(":checkbox.checkall:checked");
if (zall) {
var zname = $(zall).attr("name");
var selectallmachines = "input[name^='" + zname +"']:checked:enabled";
$( $(selectallmachines), "#mytable");
}
var arr = [];
$(":checkbox:checked").each(function(i) {
arr[i] = $(this).val();
});
});
I'm sure that it is something that I'm overlooking, but what am I missing? Would appreciate any suggestions or guidance on what I'm doing wrong, or if there's perhaps a better way to do what I'm doing.
Thanks!
You can do something like this
$('.checkall').change(function(){
$('input[id^='+this.id+']').prop('checked',this.checked);
});
when .checkall is clicked/changes - set checked property on all inputs with an id that starts with the current clicked elements id
FIDDLE
Though you probably should delegate since you are using ajax to get the elements - this is assuming #mytable exists on DOM Ready - or replace with an ancestor element that does
$('#mytable').on('click','.checkall',function(){
$('input[id^='+this.id+']').prop('checked',this.checked);
});
another alternative is to give the checkall id as a class to the relative checkboxes
$tr.append('<td><input type="checkbox" name="'+idname+'" id="'+idname+'" class="'+roomchk+'"/><label for="'+idname+'">'+machID+'</td>');
then you can do
$('#mytable').on('click','.checkall',function(){
$('input.'+this.id).prop('checked',this.checked);
});
FIDDLE

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

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