Skip to main content

jQuery store list of checkbox values in div

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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:

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.