3

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

In order to test that a submit button works 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 press the submit button it pops up a message

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

$(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 pops up when the document is ready, not when I press submit What am I doing wrong? I like the second type of code cause it is easier for me to read, but I can't figure out why it does not work

Thanks in advance for any help you can provide

Cruces
  • 3,029
  • 1
  • 26
  • 55
  • This question has been asked hundreds of times here on StackOverflow. it is a very common mistake. – jfriend00 Apr 22 '15 at 09:39
  • Other dup references [here](http://stackoverflow.com/questions/23419929/calling-the-settimeout-function-recursively-and-passing-an-anonymous-function/23419951#23419951) and [here](http://stackoverflow.com/questions/16580012/function-called-at-the-start-of-page-loading-javascript/16580400#16580400) and [here](http://stackoverflow.com/questions/26575979/jquery-deferred-done-executes-predefined-function-instantly-but-not-function-de/26576033#26576033). – jfriend00 Apr 22 '15 at 09:43

1 Answers1

5

You are invoking the function instead of passing it's reference to submit

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

Also on ready

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

Remove () of set_up_listeners

$(document).ready( 
    set_up_listeners
);
cracker
  • 4,900
  • 3
  • 23
  • 41
Vigneswaran Marimuthu
  • 2,452
  • 13
  • 16