jQuery to populate hidden input but retain existin

2019-08-25 18:38发布

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条回答
来,给爷笑一个
2楼-- · 2019-08-25 19:31

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;
  }
查看更多
登录 后发表回答