3

I have a div

    <div id="fade_bg">
        <div id="login_div">
            <form action="../classes/login/Authenticator.php" method="post">
                <p>username: <input type="text" name="username" /></p>
                <p>password: <input type="password" name="password" /></p>
                <p><input type="submit" name="login" /></p>
            </form>
            <p><a id="cancel" href="#">cancel</a>
        </div>
    </div>

That I only want to show when

<a id="login" href="">Admin login</a>

is clicked. I used

        $(function() {

            $('a#login').click(function() {
                $('#fade_bg').show();
                $('#login').hide();
            });

            $('a#cancel').click(function() {
                $('#fade_bg').hide();
                $('#login').show();
            });
        });

However, when I click the link, the div I want to appear only appears for a split second, then returns to normal as if I clicked the cancel button. Why is this happening?

Edit: No errors on the JS debugger console.

Monica
  • 1,585
  • 3
  • 23
  • 34
  • When you submit a form I believe it likes to refresh the page. Try adding `onsubmit="false"` – David Starkey May 08 '13 at 16:18
  • You'll need to prevent the default action of the anchor. In some browsers an empty href will reload the page, and a hash href will scroll to the top: – adeneo May 08 '13 at 16:18
  • 1
    firstly i think its a good idea to use e.preventDefault within your call, you need to prevent the default behaviour of the anchor as you are introducing some new functionality – Richlewis May 08 '13 at 16:19
  • 1
    looks like your answer is below – Richlewis May 08 '13 at 16:19

2 Answers2

10

Try like this:

$('#login').click(function (e) {
    e.preventDefault();
    $('#fade_bg').show();
    $(this).hide();
});

$('#cancel').click(function (e) {
    e.preventDefault();
    $('#fade_bg').hide();
    $('#login').show();
});

DEMO HERE

palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

The submit button always post the form so

<input type="submit" name="login" />

Replace it with

<input type="button" name="login" />
Milson
  • 1,525
  • 3
  • 15
  • 29