Reputation: 7059
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?
EDIT: Not jQuery or other framework please. :)
Upvotes: 3
Views: 19810
Reputation: 7059
I found the solution :)
<form onsubmit="calcRoute(); return false">
<input type="text" id="start" name="start">
<input type="submit" value="Vai">
</form>
Upvotes: 0
Reputation: 101
<input type="text" id="start" name="start" onkeypress="return calcRoute(event)">
now modify your script as follows:
function calcRoute(e) {
if (e.keyCode == 13) {
//your code
}
}
Upvotes: 0
Reputation: 72672
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/
Upvotes: 3
Reputation: 608
Probably add this in your code if you using jquery
$(document).ready(function() {
$("#start").bind('keyup',function(event){
if(event.keyCode == 13){
$("#start").click();
}
});
});
it will trigger ur button click function on pressing enter key in your text box.
If you not using jquery try this one
<input type="text" id="start" name="start" onkeydown="if (event.keyCode == 13) document.getElementById('fire_calRoute').click()">
<input type="button" id='fire_calRoute' onclick="calcRoute();" value="Go">
try this, hope it will solve your problem.
Upvotes: 0
Reputation: 101
try this:
<form onsubmit="calcRoute()">
<input type="text" id="start" name="start">
<input type="button" onclick="calcRoute();" value="Go">
</form>
i'm sure it'll work with both
Upvotes: 0