tags:

views:

232

answers:

2

Hi,

I have an ajax script executed using jquery when an input text field is changed using keyup. This part works fine. However, I also want to trigger this same keyup event when the form autoloads with some text in this input text field.

I'm auto-loading the form text field by using php to populate the form from the url (get request).

My HTML code:

<input id="code" name="code" type="text" />

My JS:

$(document).ready(function () {
  // doesn't work
  // i want to execute the code in the function specified within $('#code').keyup(function () {} below. nothing happens here.
  if ($('#code').val() != '') {
    $('#code').trigger('keyup');
  }

  // works fine
  $('#code').keyup(function () {
   // function code
  }
}

Not sure if I'm doing this right. Would appreciate if anyone could help me out on this. Thanks! :)

+1  A: 

have you tried just calling .keyup() instead of .trigger('keyup')?

another thing you could do is abstract the code you want to call into another function and call that instead of triggering a click:

$('#code').keyup(myFunction);
Jason
Hi Jason, that was exactly what I was trying to do, by moving the code into a function and calling it from there. Needless to say, I encountered other problems, like how do I make sure "this" within the function was referring to $('#code'). Would declaring var code = $('#code') in the function resolve that problem? Thanks anyway! =)
Lyon
Sorry Jason, would have specified yours as the correct answer but K Prime's was clearer for a beginner like me. :) Thanks!
Lyon
That's ok, he is correct. Glad you got it working!
Jason
+1  A: 

You need to trigger keyup (either with $('#code').trigger('keyup') or $('#code').keyup()), after binding the event handler, not before.

$(document).ready(function () {
    $('#code').keyup(function () {
        // function code
    }

    if ($('#code').val() != '') {
        $('#code').trigger('keyup');
    }
}
K Prime
Thank you so much! I actually realised this was the case a few minutes ago. Came on to the website again to say that I've resolved it, but realised you have already saw the problem. Thanks again! I actually spent a good 3 hours trying to figure this out. :S
Lyon