JQuery function works as one line, but not when I split it

I am new to javascript and html and I have a question

To test if the submit button is working correctly I used this jquery script

$(document).ready(function() {
    $("#search_form").submit(function() {
        alert("you pressed submit");
        event.preventDefault();
        return false;
    });
});

      

This works as expected, when I click the submit button the message appears

However, when I use the following code (which in theory does the same)

$(document).ready( 
    set_up_listeners()
);

function set_up_listeners() {
    $("#search_form").submit(submit_pressed());
};

function submit_pressed() {
    alert("you pressed submit");
    event.preventDefault();
    return false;
};

      

the alert appears when the document is ready, not when I click the submit button. What am I doing wrong? I like the second type of code because it's easier for me to read, but I can't figure out why it doesn't work.

Thanks in advance for any help you can provide

+3


source to share


1 answer


You are calling the function instead of passing its reference to submit

function set_up_listeners() {
    $("#search_form").submit(submit_pressed);
};

      

Also on ready



$(document).ready( 
    set_up_listeners()
);

      

Remove () from set_up_listeners

$(document).ready( 
    set_up_listeners
);

      

+5


source







All Articles