开发者

jQuery monitoring form field created by AJAX query

Preface: I am sure this is incredibly simple, but I have searched this site & the jQuery site and can't figure out the right search term to get an answer - please excuse my ignorance!

I am adding additional form fields using jQuery's ajax function and need to then apply additional ajax functions to those fields but can't seem to get jQuery to monitor these on the fly form fields.

How can I get jQuery to use these new fields?

$(document).ready(function() {
   $('#formField').hide();
   $('.lnk').click(function() {
      var t = this.id;
      $('#formField').show(400);
      $('#form').load('loader.php?val=' + t);
   });

      //This works fine if the field is already present
      var name  = $('#name');
      var email = $('#email');
      $('#uid').keyup(function () {
         var t = this; 
         if (this.value != this.lastValue) {
            if (this.timer) clearTimeout(this.timer);             
            this.timer = setTimeout(function () {
               $.ajax({
                  url: 'loader.php',
                  data: 'action=getUser&uid=' + t.value,         
                  type: 'get',
                  success: function (j) {
                     va = j.split("|");
                     displayname  = va[1];
                     mail         = va[2];
                     name.val(displayname);
                     email.val(mail);
                  }
               });
       开发者_如何学C     }, 200);  
            this.lastValue = this.value;
         }
      });
}); 

So if the is present in the basic html page the function works, but if it arrives by the $.load function it doesn't - presumably because $(document).ready has already started.

I did try:

$(document).ready(function() {
   $('#formField').hide();
   $('.lnk').click(function() {
      var t = this.id;
      $('#formField').show(400);
      $('#form').load('loader.php?val=' + t);
      prepUid();
   });
});

function prepUid(){
      var name  = $('#name');
      var email = $('#email');
     $('#uid').keyup(function () {
snip...........

But it didn't seem to work...


I think you are close. You need to add your keyup handler once the .load call is complete. Try changing this...

  $('#form').load('loader.php?val=' + t);
  prepUid();

To this...

  $('#form').load('loader.php?val=' + t, null, prepUid);


What you are looking for is the jquery live function.

Attach a handler to the event for all elements which match the current selector, now or in the future

You can do something like this:

$('.clickme').live('click', function() {// Live handler called.});

and then add something using the DOM

$('body').append('<div class="clickme">Another target</div>');

When you click the div added above it will trigger the click handler as you expect with statically loaded dom nodes.

You can read more here: http://api.jquery.com/live/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜