Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form submit on field enter key keydown? [duplicate]

I've built a listener to prevent a form from submitting on a special ocasion.

I'm using google maps autocomplete api and basically I don't want to submit the form when the users press enter and the "recommended results box" is displayed. As the users are pressing enter to choose a value from the dropdown box and not to submit the form.

I've built a listener that catches the event correctly but I don't know how to prevent the form from being submitted.

$('body').live('keydown', function(e) {
    if($(".pac-container").is(":visible") && event.keyCode == 13) {
        e.preventDefault(); // Prevent form submission
        }
    });

I tried with e.preventDefault(); but it still submits the form. The form ID is: updateAccountForm

How can I prevent it from happening?

EDIT: I must point out that it seems that listening for keypresses directly on the search input conflicts with Google API invalidating the autocomplete functions. So no $('input#search') keydown/keypress is possible

like image 349
lisovaccaro Avatar asked Dec 16 '22 20:12

lisovaccaro


1 Answers

The solution was actually pretty simple. All listeners seemed to fail however adding:

onkeydown="if($('.pac-container').is(':visible') && event.keyCode == 13) {event.preventDefault();}"

Directly to the input did the trick.

like image 132
lisovaccaro Avatar answered Dec 26 '22 20:12

lisovaccaro