pat-och pat-och - 8 months ago 129
jQuery Question

October CMS javascript event on backend repeater fields

Using October CMS for a project, I try to add a javascript event on backend repeater fields. But it seems dynamically added input field by repeater doesn't see by the javascript while it works with others input field of the same form

my script below:

<script>
$('input').on('keypress', function(e){
// only numbers
if ( charCode < 48 || charCode > 57 ) {
return false;
}
return true;
});
</script>


have you some idea to make it works ?

thanks in advance & regards,
Patrick

Jai Jai
Answer Source

You stated:-
it seems dynamically added input field by repeater doesn't see by the javascript while it works with others input field of the same form

It is a correct behavior because event binding has been done when page was loaded and you have created new elements afterwards, so event doesn't bound on those elements.

You have to use the technique which is called event delegation. Like:

  $(document).on('keypress', 'input', function(e){
      // the code 
  });

Here in this code you can change $(document) to a closest static parent like any div, form etc..

$('form').on('keypress', 'input', function(){
   // code here
});

So, the syntax is:

$(staticParent).on(event, selector, callback);  

Where staticParent is the element which is the parent element when page was loaded. It should not be a dynamically created parent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download