Make onclick function work with ENTER and "Go" button on Safari Mobile (iOS)

MultiformeIngegno picture MultiformeIngegno · Apr 28, 2013 · Viewed 18.3k times · Source

I have a form in which the button calls a function onclick:

<form>
    <input type="text" id="start" name="start">
    <input type="button" onclick="calcRoute();" value="Go">
</form>

function calcRoute() {
    var start = document.getElementById('start').value;
      var end = "My Address in Rome";
      var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
      };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

It works properly on every browser if you click on the "Go" button (<input type="button">). It doesn't if I fill the <input type="text"> and press ENTER on my keyboard (or for example push the "Go" button in iOS keyboard). So: it works if I push the input type="button", not if I press ENTER from keyboard. How can I make it work that way too? Thanks in advance

EDIT: Not jQuery or other framework please. :)

Answer

PeeHaa picture PeeHaa · Apr 28, 2013

You should really just remove that inline javascript and make that button into a real submit button. After that you can easily capture the form being submitted (wether be enter key or by submit button):

form.addEventListener('submit', calcRoute);

Demo: http://jsfiddle.net/ghK4P/