开发者

jquery trigger an event

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! :)开发者_JAVA技巧


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');
    }
}


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);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜