user4277651
user4277651

Reputation:

form submitting even after return false jquery

my simple jquery code is showing the alter box but also submiting the form. why its happening ? when enter key is pressed and if length is less than 3 then it should show error and should not submit the form, but it is submitting the form even after showing the error.

            $('#frmSearch input').keydown(function(e) {
            if (e.keyCode == 13) {
                if ($('#frmSearch input').val().length < 3) {
                    alert("SEARCH TEXT TOO SHORT");
                    return (false);
                }
                else
                {
                    $('#frmSearch').submit();
                }
            }
        });

Upvotes: 0

Views: 1462

Answers (3)

madvora
madvora

Reputation: 1747

Sometimes an Enter key can automatically submit a form by default. If you want to intercept and prevent that behavior, you can stop the default submit. I would put e.preventDefault() in your code.

Updated

$('#frmSearch input').keydown(function(e) {

    if (e.keyCode == 13) {
        //Prevents default submit
        e.preventDefault();

        if ($('#frmSearch input').val().length < 3) {
            alert("SEARCH TEXT TOO SHORT");
            return (false);
        }
        else
        {
            $('#frmSearch').submit();
        }
    }
});

Upvotes: 0

you can try so also, use the keypress not use keydown

(function ($) {
  $ ('# frmSearch input'). keypress (function (e) {
             if (e.KeyCode == 13) {
                 if ($ ('# frmSearch input'). val (). length <3) {
                     alert ("SEARCH TEXT TOO SHORT");
                     return (false);
                 }
                 else
                 {
                     $ ('# frmSearch') submit ().;
                 }
             }
         });

}) (jQuery);

Upvotes: 1

Sachin
Sachin

Reputation: 1218

Enter key automatically submits the form. You can do it like this:

$("#frmSearch").submit(function(e){
   if ($('#frmSearch input').val().length < 3) {
      e.preventDefault();
      alert("SEARCH TEXT TOO SHORT");
   }
}

and you are not handling submit event but keydown event which doesn't stop submit from calling.

Upvotes: 2

Related Questions