Jump to content

JQuery: adding events to new HTML elements


bosoxbill

Recommended Posts

I am working with Advanced Custom Fields in Wordpress and trying to get some of the input fields to total in another field when certain fields lose focus.

 

I can get this to work when the page is loaded and the fields are already on the page. However, there is a "button" (technically not a button, but this:

<ul class="acf-hl">
<li class="acf-fr">
<a href="#" class="acf-button blue" data-event="add-row">Add Row</a>
</li>
</ul>

 

) that when pressed will add rows with new input fields. The script will not work unless I save the page. Is there a way for a script to include any newly added elements to a web page?

 

Here is my code:

jQuery(document).ready(function($) {

$("div[data-name='away_players'] tr.acf-row").each(function(){
var z = $(this).find('input');
z.blur(function(){
z[3].value = (2 * parseInt(z[0].value)) + (3 * parseInt(z[1].value)) + parseInt(z[2].value);
})(jQuery); 
I've included a screen shot. When the light blue inputs lose focus they get summed and the total goes in the red input for each row. Here is the screen shot:
post-98669-0-68433800-1465957177_thumb.png

 

Link to comment
Share on other sites

IF you are saying that jquery event is triggered on current elements, but not on newly created elements, then you need to use .on(), its selector targets a parent element that is always present, it will run code on newly created row of child elements within this parent.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...