1

I have a stupid simple Jquery .js file I'm busy creating and I'm getting stuck on the first step.

I currently have it setup as shown below and yet every time I click the only button on the page (submit button for a login page), it reloads the entire page and runs the first function again.

How do i get the function to only run once

$(document).ready(function() {
    //
    //  FUNCTIONS 
    //

    function AllFade() {
        //Hide everything
        $('div').hide()

        //Fade Everything in
        $('div').fadeIn(1000);

        //Hide All Alerts
        $('.alert').hide();
    }

    function LoginCheck() {
        //Check username and pass
    }   

    //   EVENTS     

    //START SEQUENCE
    AllFade();

    //Login check on submit
    $('.btn').click(function() {
        LoginCheck();
    })
});

!! EDIT !!

The button's coding is this exactly:

<button class="btn btn-large btn-primary">Sign in</button>

Would that still cause a reload?

Skowt
  • 411
  • 2
  • 6
  • 15
  • 2
    Your button is an anchor tag with href="", therefore it's going to "" which is the current page, causing a reload. This is the default behavior of an anchor tag. – Kevin B Sep 04 '13 at 19:53
  • 1
    possible duplicate of [Prevent a link to reload page](http://stackoverflow.com/questions/18575623/prevent-a-link-to-reload-page) – Sergio Sep 04 '13 at 19:54

2 Answers2

6

You need to prevent the submit (event) of the form with .preventDefault() so it will not do the default behaviour: submit the form and reload the page.

$('.btn.btn-large.btn-primary').click(function(event) { 
   //if only button on page you can have just $('button')
    event.preventDefault()
    LoginCheck();
})

You can also add type="button" if you do not want to use the button as a submit button, because the button element has a default type of submit:

<button type="button" class="btn btn-large btn-primary">Sign in</button>


You can read more here:

jQuery docs: .preventDefaul()

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • Although the behavior is similar (identical), the `preventDefault` being called isn't that of the native Event. It's of jQuery's `Event`. I don't think MDN is the right place to cite. http://api.jquery.com/event.preventDefault/ – Ian Sep 04 '13 at 20:02
  • 2
    Good point @Ian, MDN came up first in my search. Just corrected it. Thanks – Sergio Sep 04 '13 at 20:03
  • Edited main question. Please check again @Sergio – Skowt Sep 04 '13 at 20:31
  • @Sergio, works as it should. Thanks very much for the help! :D – Skowt Sep 05 '13 at 05:05
1

Add an event in there and use .preventDefault()to prevent the page from reloading.

$('.btn').click(function(e) {
    e.preventDefault();
    LoginCheck();
});
Tricky12
  • 6,752
  • 1
  • 27
  • 35