Insert comma separated values on multiple buttons in input type text

Picture of Amitpal Singh
Amitpal Singh
April 30, 2023

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=""> 

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.