pawel7318
pawel7318

Reputation: 3583

append to change function

I have 3 forms: foo, bar and baz which contains same set of checkboxes:

<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>

Then I have a function like this:

function clone_checkboxes_values(src_form, src_prefix, dst_prefix) {
  $('#' + src_form + ' input:checkbox').change(function() {
     $('#' + dst_prefix + this.id.replace(src_prefix, '')).prop('checked', this.checked);
 });
}

which I run:

clone_checkboxes_values('foo_form', 'foo_select', 'bar_select');

and it makes every checkbox change at foo to be copied to bar. I wish to run another call to the clone_checkboxes_values to copy changes to baz as well (don't overwrite change(function(){}) but append to it. I have no clue how to make it. Please help.

This is the Fiddle with all prepaded.

Upvotes: 0

Views: 60

Answers (2)

Edem
Edem

Reputation: 402

Doesn't this work?

clone_checkboxes_values('foo_form', 'foo_select', 'baz_select');

jQuery doesn't overwrite event handlers by default. In other words, any subsequent call to change() only adds a new event handler to the previous. It works the same for other event binding functions such as click(). The event handlers will be sequentially run in the order they were bound to the event.

In other words, if I theoretically execute the following calls,

$(<selector>).bind(<event>, <function1>)
$(<selector>).bind(<event>, <function2>)

when <event> occurs, function1 will be executed, then will follow function2.

Upvotes: 0

JLRishe
JLRishe

Reputation: 101690

I think you've already figured it out. All you need to do is call this:

clone_checkboxes_values('foo_form', 'foo_select', 'baz_select');

Perhaps it wasn't working because you were missing a ' before baz_select.

http://jsfiddle.net/5a3Jj/1/

Upvotes: 1

Related Questions