2

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.

1 Answer 1

2

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(', '));

    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.