JavaScript
Article

jQuery store list of checkbox values in div

By Sam Deering

Just say you wanted to store a list in a text area so that when a checkbox is ticked it appended the item to the list. Likewise when the checkbox was unchecked in removed the item from the list. This is how you might go about doing such a crazy thing! ;-)

Demo

/*when a user selects interest in an addtional service, add this to the additionalServices div*/
$('input[type="checkbox"]').bind('change', function() {
	var alsoInterested = '';
	$('input[type="checkbox"]').each(function(index, value) {
		if (this.checked) {
			/*add*/ /*get label text associated with checkbox*/
			alsoInterested += ($('label[for="'+this.name+'"]').html() + ', ');
		}
	});
	if (alsoInterested.length > 0) {
		alsoInterested = 'I am also interested in booking: ' + alsoInterested.substring(0,alsoInterested.length-2) + '.';
	} else {
		alsoInterested = 'I am not interested in additional services.';
	}
	
	$('#additionalServices').html(alsoInterested);
	//console.log($('#additionalServices').html());
});

Code is based on the following HTML:

  • Nick

    No demo? I hate when there’s no demo. grrr

    • Meh

      Me too, a total waste of time

      • http://jquery4u.com/ jQuery4u

        Hi guys, sorry about that, I’ve added a demo for you.
        Sam

  • Nick

    Your code doesn’t work, because you need to change

    $(‘#additionalServices’).val(alsoInterested);

    to be

    $(‘#additionalServices’).html(alsoInterested);

    Ya know, if you had included a demo, you probably would have caught this. ^_-

    Love the site. I love stuff like this, snippets of Jquery code that I can dissect so to understand how it works, then implement that into my own jQuery projects.

    • jquery4u

      @Nick – Thanks! I’ll update the post with the code fix. Sorry there was no demo I was planning to do one but got held up with other posts! Thanks again and keep up the good work!

  • terveg

    seems if I have something like first option by default checked=”checked” …this example doesn’t work. I must have checked=”checked”, we must check if there has being something checked already and use that…could you please update your nice JS ? thanks!

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.