Skip to content

Instantly share code, notes, and snippets.

@kirk7880
Created October 6, 2012 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirk7880/3844611 to your computer and use it in GitHub Desktop.
Save kirk7880/3844611 to your computer and use it in GitHub Desktop.
Update text input after selecting one or more checkbox
<!DOCTYPE html>
<html>
<head>
<style>
div {
color:blue;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form>
<p>
<label for="hourly">Hourly</label>
<input type="checkbox" name="newsletter" checked="checked" value="Hourly" id="hourly"/>
<label for="hourly">Daily</label>
<input type="checkbox" name="newsletter" value="Daily" id="daily" />
<label for="hourly">Weekly</label>
<input type="checkbox" name="newsletter" value="Weekly" id="weekly" />
<label for="hourly">Monthly</label>
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" id="monthly" />
<label for="hourly">Yearly</label>
<input type="checkbox" name="newsletter" value="Yearly" id="yearly" />
</p>
<input type="text" value="" name="myname" id="foo"/>
</form>
<div></div>
<script type='text/javascript'>
var checkboxes = $('form > p > input:checkbox');
// updates the text input with the selected values...
var update = function() {
var values = [];
$('form > p > input:checked').each(function(idx, cb) {
values.push($(this).val());
});
$('#foo').val(values.join(', '));
};
// count the number of selected items...
var count = function() {
var n = $("input:checked").length;
$("div").text([n, 'box selected!'].join(' '));
};
// bind to the checkbox for clicks
// update the input field
// count the number of selected items
$(checkboxes).on('click', function(e) {
update();
count();
});
update();
count();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment