How to retrieve checkboxes values in jQuery How to retrieve checkboxes values in jQuery jquery jquery

How to retrieve checkboxes values in jQuery


Here's one that works (see the example):

 function updateTextArea() {              var allVals = [];     $('#c_b :checked').each(function() {       allVals.push($(this).val());     });     $('#t').val(allVals);  } $(function() {   $('#c_b input').click(updateTextArea);   updateTextArea(); });

Update

Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.


You can also return all selected checkboxes value in comma separated string.This will also make it easier for you when you send it as a parameter to SQL

Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string

And here is the javascript

function showSelectedValues(){  alert($("input[name=chkboxName]:checked").map(function () {    return this.value;  }).get().join(","));}

Here is the HTML sample

<html>  <head> </head> <body>  <div>   <input name="chkboxName" type="checkbox" value="one_name" checked>   <input name="chkboxName" type="checkbox" value="one_name1">   <input name="chkboxName" type="checkbox" value="one_name2">  </div>   </body> </html>


Your question is quite vague but I think this is what you need:

$(function() {     $('input[type="checkbox"]').bind('click',function() {        if($(this).is(':checked')) {            $('#some_textarea').html($(this).val());         }   });});

Edit: Oh, okay.. there you go... You didn't have the HTML up before. Anyways, yeah, I thought you meant to put the value in a textarea when it gets clicked. If you want the checked checkboxes' values to be put into the textarea (maybe with a nice comma-seperation) on page load it would be as simple as:

$(function() {     $('#c_b input[type="checkbox"]:checked').each(function() {         $('#t').append(', '+$(this).val());    });});

Edit 2 As people have done, you can also do this to shortcut the lengthy selector I wrote:

$('#c_b :checkbox:checked').each(function() {    $('#t').append(', '+$(this).val());});

... I totally forgot about that shortcut. ;)