Insert comma separated values on multiple buttons in input type text
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$('.baths').on('change', function() {
var vals = [];
$('.baths:checked').each(function(){ //could also use .map here
vals.push($(this).val());
});
$('.all_baths').val(vals.join(','));
console.log($('.all_baths').val());
});
<input class="btn btn-default baths" name="baths" type="checkbox" value="1">
<input class="btn btn-default baths" name="baths" type="checkbox" value="2">
<input class="btn btn-default baths" name="baths" type="checkbox" value="3">
<input class="btn btn-default baths" name="baths" type="checkbox" value="4">
<input class="btn btn-default baths" name="baths" type="checkbox" value="5+">
<input class="all_baths" type="text" value="">
Codepen:
Otherwise – you need to keep track of what’s been clicked on in an array:
var baths = [],
$baths = $('.baths'),
$all_baths = $('.all_baths');
$baths.on('click', function(){
var $this = $(this),
val = $this.val();
//Already added - remove it
if(baths.indexOf(val) > -1) {
baths.splice(baths.indexOf(val), 1);
}
//not added - add it
else {
baths.push(val);
}
$all_baths.val(baths.join(','));
console.log($all_baths.val());
});
<input class="btn btn-default baths" name="baths" type="button" value="1">
<input class="btn btn-default baths" name="baths" type="button" value="2">
<input class="btn btn-default baths" name="baths" type="button" value="3">
<input class="btn btn-default baths" name="baths" type="button" value="4">
<input class="btn btn-default baths" name="baths" type="button" value="5+">
<input class="all_baths" type="text" value="">