Created
October 6, 2012 11:00
Update text input after selecting one or more checkbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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