JavaScript
Article
By Sam Deering

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:

--ADVERTISEMENT--

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account