I\'d like to populate a hidden input with the values of selected checkboxes with a space between these values. I\'ve tried the following which in theory should work but it i
You just need to change your selector and attach your script to some event. For example:
$('input[type=checkbox]').change(function() {
var vals = $('input[type=checkbox]:checked').map(function() {
return $(this).val();
}).get().join(',');
$('#tags').val(vals);
});
See this DEMO.
:checkbox
is deprecated
Instead of
$(':checkbox:checked')
Use
$('input[type="checkbox"]:checked')
Also none of the checkboxes are checked
when the document is Ready
.. Set them first and then try ...
HTML
<input type="checkbox" value="test1" id="test1" checked><label>Test</label>
<input type="checkbox" value="test2" id="test2" checked><label>Test2</label>
<input type="checkbox" value="test3" id="test3"><label>Test3</label>
<input type="text" value="" id="tags">
Javascript
function Populate(){
vals = $('input[type="checkbox"]:checked').map(function() {
return this.value;
}).get().join(',');
console.log(vals);
$('#tags').val(vals);
}
$('input[type="checkbox"]').on('change', function() {
Populate()
}).change();
Check Fiddle