0

I am making A ajax login form great progress so far thanks to A few users on stack flow so far.

Now when I check all the fields out if it responds to enter being pressed it is working fine except when I tab to the submit button it is submitting the data twice according to the Chrome networking tab.

I think it is executing the .click function aswill as the .keycode function.

How can i say in the code if keycode enter is false and I click the button execute the function or if its true don't execute the .click function.

$(document).ready(function () {
    $('#field').keyup(function (e) {
        if(e.keyCode == 13) {
            //If enter is pressed vailidate the form
            $.ajax({
                url: 'ajax/check.php',
                type: 'post',
                data: {
                    method: 'fetch'
                },
                success: function (data) {
                    $('.chat .messages').html(data);
                }
            });
        };
    });
    $('#submit').click(function () {
        alert('Do something here this is just a test');
    });
});
tshepang
  • 12,111
  • 21
  • 91
  • 136
Spudster
  • 69
  • 1
  • 11

1 Answers1

1

just add preventDefault and return false to the keyup function like that:

$('#field').keyup(function (e) {
    if(e.keyCode == 13) {
        //If enter is pressed vailidate the form
        e.preventDefault();
        $.ajax({
            url: 'ajax/check.php',
            type: 'post',
            data: {
                method: 'fetch'
            },
            success: function (data) {
                $('.chat .messages').html(data);
            }
        });
     return false;
    };       
});

This will prevent the form from submitting when users press ENTER.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
akhilless
  • 3,169
  • 19
  • 24
  • Why preventing default behaviour if you are always returning false? – A. Wolff May 25 '13 at 12:48
  • @roasted you are write. should return false only when enter is pressed. updated my answer. thanks a lot for pointint that out. – akhilless May 25 '13 at 12:54
  • Still doesent work. Not sure if I am explaining enough but I have A snapshot that should help http://tinypic.com/view.php?pic=opyd60&s=5 – Spudster May 25 '13 at 13:10