Need to append / delete id into hidden field on "change"

296 views Asked by At

I ve got numérous checkboxes in my page, each time I click a checkbox, I get the id im interested in and I fill a hidden form. My script is working but if I unclick the checkbox, it should delete the id from the hidden field (right now it appends again the id in the hidden field). How can I writte such a script ? Here's my code so far:

$(document).ready(function() {
    var string = "";


  $('.checkbox').on('change', function() {
    var subscription_id = $(this).parent().attr('id');
    if(string == "") {
      string = subscription_id;
    } else {
      string = string + ", " + subscription_id;
    }
    $('#select_players').val(string);
    $('#subscription_ids_export').val(string);
  })
})
1

There are 1 answers

4
Rory McCrossan On BEST ANSWER

You can simplify this by retrieving only the subscription_id values from checkboxes which are checked instead of adding/removing values each time.

Try this:

$('.checkbox').on('change', function() {
    var subscriptionIds = $('.checkbox:checked').map(function() {
        return $(this).parent().prop('id');
    }).get().join(',');
    $('#select_players').val(subscriptionIds);
    $('#subscription_ids_export').val(subscriptionIds);
})

Example fiddle