copy checkboxes marks to another form

故事扮演 提交于 2019-12-25 06:34:13

问题


I have 2 forms:

foo:

<form id="foo_form" method="post" action="foo">
  <input class="foo checkbox" id="foo_select_1" name="ids[]" type="checkbox" value="1" />
  <input class="foo checkbox" id="foo_select_2" name="ids[]" type="checkbox" value="2" />
  <input class="foo checkbox" id="foo_select_3" name="ids[]" type="checkbox" value="3" />
  ...
  <input type="submit" value="action 1" />
</form>

bar:

<form id="bar_form" method="post" action="bar">
  <input class="bar checkbox" id="bar_select_1" name="ids[]" type="checkbox" value="1" />
  <input class="bar checkbox" id="bar_select_2" name="ids[]" type="checkbox" value="2" />
  <input class="bar checkbox" id="bar_select_3" name="ids[]" type="checkbox" value="3" />
  ...
  # some other input fileds here
  <input type="submit" value="action 2" />
</form>

I need JS (jQuery) that for every change of checkbox at foo will change corresponding checkbox at bar.

The main goal for that is to have 2 different actions for the same checkboxes. I want to hide those at bar with CSS and leave only submit button visible. All is described here


回答1:


This will do it:

Fiddle

$(document).ready(function(){
    $('#foo_form input:checkbox').change(function(){
       $('#bar_' + this.id.replace('foo_', '')).prop('checked', this.checked); 
    });
});



回答2:


This seems like a very strange thing to have to do. Do you just need to get a copy of the current values from the #bar_form form when a box is checked? If so, I would look into using the data $('#foo_form').serializeArray() gives you after a change event on it.

$('#foo_form').on('change', function () {
  var $form = $(this);
  console.table($form.serializeArray());
});


来源:https://stackoverflow.com/questions/23198407/copy-checkboxes-marks-to-another-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!