246

How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?

Just like this code:

<html>
  <head>
  </head>

  <body>
    <div id="c_b">
      <input type="checkbox" value="one_name" checked>
      <input type="checkbox" value="one_name1">
      <input type="checkbox" value="one_name2">
    </div>  

    <textarea id="t"></textarea>
  </body>
</html>

If the id="c_d" is updated by Ajax, the below of altCognito's code doesn't work. Is there any good solution?

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
lanqy
  • 3,001
  • 5
  • 25
  • 18

14 Answers14

325

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
cgp
  • 41,026
  • 12
  • 101
  • 131
  • 2
    Ah ha! Excellent. You've taken into account both likely scenarios. Good work sir. ;) – KyleFarris Apr 24 '09 at 15:19
  • How can we 'check' the box with a given value/label ? say "one_name2"? – Amitd Mar 26 '10 at 06:58
  • 6
    I like to use map for stuff like this: $(':checked', '#c_b').map(function (i,cb) { return cb.value} ).get(). Also, this is just personal preference, but I would separate getting the values from changing the text areas, something like: $(function() { $('#c_b input').click($('#t').val($(':checked', '#c_b').map(function (i,cb) { return cb.value} ).get())); $('#c_b input:first').triggerHandler('click'); }); – Brandon Nov 05 '11 at 07:14
  • use `$(document).on("click", "#c_b input", updateTextArea);` instead to get around ajax'y problems. – Goldentoa11 Oct 14 '14 at 20:09
  • 1
    not sure if this is just in IE(11), but shouldn't it be `$('#c_b:checked')` (emphasis on the spacing) ? – AceMark Dec 14 '14 at 16:06
  • without the space, it's only going to evaluate the pseudo selector :checked against the #c_b element, not all of the children. That *shouldn't* be an IE11 thing – cgp Dec 18 '14 at 21:12
130

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>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mohamed ElSheikh
  • 1,369
  • 1
  • 8
  • 5
  • I just stumbled upon this while looking for a way to get all the values of checked checkboxes of a given name and it works for me with two small issues. 1) every time I check a box other than the first one, it toggles the checkmark in the first one. 2) When I try to set this to an array so that I can access the information later, it crashes. – Reverend Bubbles Dec 12 '14 at 05:24
  • 3
    This is honestly the best answer. Very simple. I would of removed the "function" and "alert" as that confuses some people, But the code is simple, well-done. – tmarois Aug 14 '16 at 01:02
  • showSelectedValues also works for decoding groups of radio buttons too that have the same name – Matthew Lock Aug 24 '16 at 08:42
66

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

KyleFarris
  • 17,274
  • 5
  • 40
  • 40
8

Thanks altCognito, your solution helped. We can also do this by using name of the checkboxes:

function updateTextArea() {         
   var allVals = [];
   $('[name=chkbox]:checked').each(function() {
      allVals.push($(this).val());
   });
   $('#t').val(allVals)
} 
$(function() { 
    $('#c_b input').click(updateTextArea);
    updateTextArea();
});
halfer
  • 19,824
  • 17
  • 99
  • 186
Harpreet Bhatia
  • 186
  • 5
  • 19
6

The following may be useful since I got here looking for a slightly different solution. My script needed to automatically loop through input elements and had to return their values (for jQuery.post() function), the problem was with checkboxes returning their values regardless of checked status. This was my solution:

jQuery.fn.input_val = function(){

    if(jQuery(this).is("input[type=checkbox]")) {
        if(jQuery(this).is(":checked")) {
            return jQuery(this).val();
        } else {
            return false;
        }
    } else {
        return jQuery(this).val();
    }
};

Usage:

jQuery(".element").input_val();

If the given input field is a checkbox, the input_val function only returns a value if its checked. For all other elements, the value is returned regardless of checked status.

Andy
  • 3,141
  • 3
  • 27
  • 22
  • it really works fine, thanks a lot... I just changed the "return jQuery(this).val();" to "return true;" because it's a checkbox in my case I just need to know if it's checked or not.. thanks! – TCB13 Aug 07 '11 at 02:20
5

Here's an alternative in case you need to save the value to a variable:

var _t = $('#c_b :checkbox:checked').map(function() {
    return $(this).val();
});
$('#t').append(_t.join(','));

(map() returns an array, which I find handier than the text in textarea).

shabeer90
  • 5,161
  • 4
  • 47
  • 65
pgcd
  • 538
  • 6
  • 13
3
 function updateTextArea() {         
     var allVals = $('#c_b :checked').map(function() {
       return $(this).val();
     }).get();
     $('#t').val(allVals)
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });
satoru
  • 31,822
  • 31
  • 91
  • 141
3
$(document).ready(function() {
  $(':checkbox').click(function() {
    var cObj = $(this);
    var cVal = cObj.val();
    var tObj = $('#t');
    var tVal = tObj.val();
    if (cObj.attr("checked")) {
      tVal = tVal + "," + cVal;
      $('#t').attr("value", tVal);
    } else {
      //TODO remove unchecked value.
    }
  });
});
cela
  • 2,352
  • 3
  • 21
  • 43
  • 1
    You've way over-complicated it. Also, you generally don't set the value of a textarea with the value parameter--the value of a textbox is it's innerHTML. And if you were to set some element's value, it's normally best to use the 'val()' method for browser abstraction purposes. – KyleFarris Apr 24 '09 at 15:18
2

A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:

var checkedCities = $('input[name=city]:checked').map(function() {
    return this.value;
}).get();

Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:

while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
<?php } ?>

Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)

This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.

shabeer90
  • 5,161
  • 4
  • 47
  • 65
zeeshan
  • 4,913
  • 1
  • 49
  • 58
2
$("#t").text($("#cb").find(":checked").val())
mkoryak
  • 57,086
  • 61
  • 201
  • 257
2

Anyway, you probably need something like this:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

Note that in your example code you should put the checkboxes in a form.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
  • 2
    This is wrong, `is` returns a boolean value, a boolean value doesn't have `val` method. – Ram Jan 28 '13 at 06:13
0

I have had a similar problem and this is how i solved it using the examples above:

 $(".ms-drop").click(function () {
        $(function showSelectedValues() {
            alert($(".ms-drop input[type=checkbox]:checked").map(
               function () { return this.value; }).get().join(","));
        });
    });
sam
  • 320
  • 3
  • 14
0

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);
sonida
  • 4,411
  • 1
  • 38
  • 40
0

If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:

$(":checkbox").click(function(){
  $("#id").text(this.value)
})
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
duckyflip
  • 16,189
  • 5
  • 33
  • 36