Stack Exchange
Put the selected checkbox into a textbox using jquery
How to put the selected checkbox into a textbox using jquery in order of the selected by the user? Everytime I select a random checkbox, the value of the textbox are depends on the pattern of the checkbox list. Here's my code:
<label>Favorite activities and areas: (Please check the box in order of priorities)</label>
<input type="checkbox" class="chckbox" value="C"/>C
<input type="checkbox" class="chckbox" value="C#"/>C#
<input type="checkbox" class="chckbox" value="PHP"/>PHP
<input type="checkbox" class="chckbox" value="Javascript"/>Javascript
<input type="checkbox" class="chckbox" value="Java"/>Java
<hr>
<input type="text" id="subject_areas" placeholder="Selected Checkboxes" disabled>

and here's my jquery code:
<script type="text/javascript">
  $(document).ready(function(){
   $('.chckbox').click(function(){
   var text = "";
   $('.chckbox:checked').each(function(){
    text += $(this).val() + ', ';
   });
   text = text.substring(0,text.length-2);
   $('#subject_areas').val(text);
   });
 });
</script>

For example I select PHP and then I select C then the value of the textbox are "C, PHP" and that is wrong. The I want value are "PHP, C". Please help me. Thank you.

One way would be to have an array variable set which you add to, or remove from depending on the checked property
$(document).ready(function(){
    //Set your array variable
    var checkboxValues = [];

    $('.chckbox').change(function(){
        var $this = $(this),
            val = $this.val();
        //Check if checkbox is checked
        if($this.prop('checked')){
            //Add value to array
            checkboxValues.push(val);
        }else{
            //Get index of current value
            var index = checkboxValues.indexOf(val);

            //Remove value from array
            checkboxValues.splice(index,1);
        }

        //Use join() for a "cleaner" approach (no trimming required)
        $('#subject_areas').val(checkboxValues.join(', '));

    });
});

