[jquery] How to retrieve checkboxes values in jQuery

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?

This question is related to jquery html checkbox

The answer is


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.


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.


 function updateTextArea() {         
     var allVals = $('#c_b :checked').map(function() {
       return $(this).val();
     }).get();
     $('#t').val(allVals)
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

$(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.
    }
  });
});

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>

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(","));
        });
    });

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


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.


$("#t").text($("#cb").find(":checked").val())

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

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

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

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


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?