jQuery to populate hidden input but retain existin

2019-08-25 19:12发布

问题:

I have the following code to populate a hidden input form with the values of all the checkboxes on a page, however I also want to retain the prepopulated values of the checkbox but can't work out how to do this.

Here's my current code, any help would be most appreciated!

$(function(){

  function Populate(){
  vals = $('input[type="checkbox"]:checked').map(function() {
      return this.value;
  }).get().join(', ');
  console.log(vals);
  $('#hidden_form_id').val(vals);
  }

  $('input[type="checkbox"]').on('change', function() {
  Populate()
  }).change();

});

回答1:

You can modify your statement

Change

$('#hidden_form_id').val(vals);

To

$('#hidden_form_id').val($('#hidden_form_id').val() + vals);

You may use += operator to retain existing value using javascript

$('#hidden_form_id')[0].value += vals;

You code would be

 function Populate(){
  vals = $('input[type="checkbox"]:checked').map(function() {
      return this.value;
  }).get().join(', ');
  console.log(vals);
  $('#hidden_form_id')[0].value += vals;
  }