0

Before I send the data from a form to a Rails controller, I need to do some javascript work yet.

This is (in short) my form:

<form action="/results" class="search_users" method="POST">
  ...
  <a class='search_users_btn' href='' id="search_users_form">
    <span class="streamline" aria-hidden="true">Search</span>
  </a>
</form>

When is clicked the Search button, then this piece of JS handles that:

  $(".search_users_btn").click(function(e) {
    var location;
    e.preventDefault();
    location = $(".location_user").val();
    $.when(geocodeFrom(location)).done(function() {
      $(".search_users").submit();
    });
  });

The problem is when a user hits ENTER, because then the javascript code above is not executed. I've tried to add following:

$(".search_users").keypress(function(ev){
   if (ev.keyCode == 13) {
    console.log('xx'); 
    //$("form")[0].submit();
   }
});

But this snippet doesn't handle when a user hit ENTER and the browser immediately sends the form to controller.

How to handle the situation when user presses ENTER in Javascript?

user984621
  • 46,344
  • 73
  • 224
  • 412

1 Answers1

2

I think ENTER triggers a submit in a form, try this :

$(".search_users").keypress(function(ev){
   if (ev.keyCode == 13) {
    ev.preventDefault();
    console.log('gotcha'); 
    //$("form")[0].submit();
   }
});

but you could also use a standard button and handle the submit event on the form, do your processing, and then make an ajax call to the (php?) processing page :

$(".search_users").on("submit", function(ev){
   ev.preventDefault(); //prevents the original submit

    //information processing ...

    //AJAX call to the form processing page ...

   }
});
sodawillow
  • 12,497
  • 4
  • 34
  • 44