javascriptjquerydocument-readykeyup

How to run a Javascript/Jquery Function using both $(document).ready(function() and Another Event Function?


I'm not a javascript/jquery coder, and not sure if what I'm trying to do is possible.

I have a html/php/ajax form that is updated an sql database as the user fills it out. As they fill the form, there is a progress bar ran by javascript/jquery that updates as the user types in the input. The start of the function looks like this:

$("#update input").keyup(function() {

This works great. My problem is when the page is reloaded. My code is pulling sql data from the database to fill the value of every input on the page that has a value so that a user can come back and completely the form later. When the user reloads the page, the only way for the script to activate is if the user types in an input field.

I thought I would fix the issue by changing the my initial javascript/jquery function with $(document).ready(function() . This caused the script to only run when the page was loaded and not when the form was being filled out. I need both the script to run on page ready, and when a user is typing in the input filled. Is there a way I can run both $(document).ready(function() AND $("#update input").keyup(function() { simultaneously? Or is there a better why to accomplish this? Thanks!

Let me know if I need to post more code.


Solution

  • Here's a generic approach attaching declared functions to events.

    function handler (e) {}
    element.addEventListener('click', handler);
    

    You're free to call handler everywhere, also inside $(document).ready, or if there's no other code in your DOMReady handler, you can just pass a reference as an argument:

    $(document).ready(handler);
    

    In your specific case you most likely want something like this:

    $(document).ready(function () {
      function handler (e) {...}
      handler();
      $("#update input").keyup(handler);
    });
    

    If the handler function uses the event object (e in the example), in modern browsers it's also available as a global event object, or in jQuery, e.originalEvent. The object doesn't exist if there's no event fired, though, in that case you've to pass a fake event object, containing the provided properties, to the handler, if it is needed.