0

I've the following HTML:

    <a id="foo">Click Me</a>

    <form action="" method="post">
        <input type="submit" value="submit">
    </form>

    <script type="text/javascript">

        $(function() {
            $('#foo').click(function() {
                alert('hello');
            });
        });

    </script>

As you can see, "Click me" works fine until I click the submit button (which reloads the page).

How can I prevent this from happening so that "Click me" works as expected even after form submission?

Note: Here's what's inside my <head>:

<head>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>

Update: I tried removing

<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" /> in the head tag, it works, however this CSS file is an essential part of Jquery Mobile.

Gajotres
  • 57,309
  • 16
  • 102
  • 130
IMB
  • 15,163
  • 19
  • 82
  • 140

2 Answers2

2

There are few possibilities.

You can add attribute data-ajax="false" to your form. Because of this your form will act as a normal form. Without it jQuery Mobile will handle form submitting and this is something you don t probably want.

<form action="" method="post" data-ajax="false">
    <input type="submit" value="submit">
</form>

Other solution is to change how you bind click event. Instead of your way you should use modern solution like this:

$(document).on('click','#foo',function() {
    alert('hello');
});

One last thing. Unless you know what you are doing don't use this code to bind a click event on DOM ready:

    $(function() {
        $('#foo').click(function() {
            alert('hello');
        });
    });

Unlike pure jQuery, jQuery Mobile uses different logic. This is because when document ready triggers jQuery Mobile page is usually still not fully loaded and enhanced inside a DOM. Because of this jQM developers have created page events. If you want to find more read my other answer about that topic: jQuery Mobile: document ready vs page events

Community
  • 1
  • 1
Gajotres
  • 57,309
  • 16
  • 102
  • 130
0

You can change this:

   <input type="submit" value="submit">

For:

   <input type="button" value="submit">

Tell me that this is.. :D

Lito
  • 2,309
  • 1
  • 23
  • 29