-1

Adding an event handler to dynamically created elements can be handled as shown here:

In jQuery, how to attach events to dynamic html elements?

$('body').on('click', 'a.myclass', function() {
    alert( $(this).text() );
});

However say I want to then perform an action on elements that were also added dynamically.

In the sample below $('inout.wp')s are being added after this code has run and I wish to validate them all using jQuery Validator when the handler fires:

<input type="text" name="wp_address_0" placeholder="Enter a Town, City or Postcode" id="wp_address_0" class="geocode wp">

<script>
$('body').on('click', 'a.myclass', function() {
    $('input.wp').valid();
});
</script>

I though perhaps I could use .find for this:

$('body').on('click', 'a.myclass', function() {
    $("#waypoints").find('input.wp').valid();
});

But it doesn't help. How can I achieve this?

Community
  • 1
  • 1
gpcola
  • 969
  • 5
  • 15
  • 26
  • It would be helpful to the reader to see the HTML markup of the newly added elements that you want to validate. Depending on the markup & situation, some might need to use the `rules('add')` method for dynamically added HTML. – Sparky Aug 23 '13 at 13:47
  • @sparky - the way the automated rules were working wasn't a problem, my problem was simply identifying which elements to apply them to *programatically*. The submit was working applying the rules correctly but I wanted to recheck validity when the goal posts had been moved. – gpcola Aug 23 '13 at 14:26
  • My point is that if you show the markup, this would be more clear to _others seeking help_. There are many different ways to use this plugin. – Sparky Aug 23 '13 at 14:35
  • @sparky - point taken however I've got multiple addClassRules and custom validation functions so it probably would only serve to confuse in this case. – gpcola Aug 23 '13 at 14:47

2 Answers2

0

Replace

$('body').on(

with

$(document).on(
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

Ok so this was way easier than I thought and I should have realised BEFORE asking...

$('body').on('click', 'a.myclass', function() {
    $('#waypoints input.wp').valid();
});

As long as you reference a static container for the dynamic elements in the selector they appear to be found.

gpcola
  • 969
  • 5
  • 15
  • 26