tags:

views:

75

answers:

4

I found something interesting in jQuery, and I wanted to run it by some folks who understand it better than me to see if there is a solution for it. So I want to post back the scroll position of the page when submitting all forms on my page. I can do this by doing the following:

$('form').submit(function() {
    $(this).append('<input type="hidden" name="scroll_position" value="' + $(document).scrollTop() + '" />');
    return true;
}

This works as expected when user click or presses enter on the submit button, but there are times where I fire the .submit() event. Example of this:

$('button').click(function() {
    ...
    // Doing something special here
    ...
    $(this).parents('form')[0].submit();
}

How would I go about getting my custom submit callback to be called whenever the page is submitted regardless of it being initiated by a .submit() call or the user submitting a form?

+1  A: 

You can create a function for that and call it before submitting:

function storePosition(){
  $('form').append('<input type="hidden" name="scroll_position" value="' + $(document).scrollTop() + '" />');
}

Later you can do:

$('form').submit(function() {
    storePosition();
    return true;
}

Or:

$('button').click(function() {
    ...
    // Doing something special here
    ...

    storePosition();
    $(this).parents('form')[0].submit();
}
Sarfraz
+1  A: 
function myFrmSubmit(){
    $(this).append('<input type="hidden" name="scroll_position" value="' + $(document).scrollTop() + '" />');
    return true;
}

$('form').submit(myFrmSubmit);
$('button').click(function() {
    ...
    // Doing something special here
    ...
    myFrmSubmit();
    $(this).parents('form')[0].submit();
}
Ismail
+2  A: 

No need to make new function, if you don't want. You just have to use jquery's .submit() and your work is done. Check the difference.

$('button').click(function() {
    ...
    // Doing something special here
    ...
    var form = $(this).parents('form')[0];
    $(form).submit();
}

Happy Coding.

simplyharsh
perfect. I guess I would be interesting in learning whats the difference between: $(this).parents('form')[0].submit(); and var form = $(this).parents('form')[0]; $(form).submit();
karlw
Please look at my answer.
Ismail
A: 

Is this what you are looking for?

Is is possible to bind a submit() function before any existing onsubmit/submit?

Ismail