How to retrieve checkboxes values in jQuery

JqueryHtmlCheckbox

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - 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.

Solution 2 - Jquery

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>

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Solution 5 - Jquery

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.

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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.

Solution 11 - Jquery

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.

Solution 12 - Jquery

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

Solution 13 - Jquery

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

Solution 14 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlanqyView Question on Stackoverflow
Solution 1 - JquerycgpView Answer on Stackoverflow
Solution 2 - JqueryMohamed ElSheikhView Answer on Stackoverflow
Solution 3 - JqueryKyleFarrisView Answer on Stackoverflow
Solution 4 - JqueryHarpreet BhatiaView Answer on Stackoverflow
Solution 5 - JqueryAndyView Answer on Stackoverflow
Solution 6 - JquerypgcdView Answer on Stackoverflow
Solution 7 - JqueryView Answer on Stackoverflow
Solution 8 - JquerysatoruView Answer on Stackoverflow
Solution 9 - JquerymkoryakView Answer on Stackoverflow
Solution 10 - JqueryPim JagerView Answer on Stackoverflow
Solution 11 - JqueryzeeshanView Answer on Stackoverflow
Solution 12 - JqueryduckyflipView Answer on Stackoverflow
Solution 13 - JquerysamView Answer on Stackoverflow
Solution 14 - JquerysonidaView Answer on Stackoverflow