0

I want to call a function when I press enter in the input field. The problem is, that it just reloads the page at the moment, and doesn't call the JavaScript. The JavaScript works without any problems, when I'm pressin the button. Now I want to have the same result, when I press enter.

This is my form

<form onSubmit="changeView()">
<input type="text" value="London" name="region" id="region">
<input type="button" onClick="changeView()" name="mySubmit" value="Search" >
</form>

I also tried to put this into the text field onKeydown="Javascript: if (event.keyCode==13) changeView();

But it didn't really help. This is my JavaScript function

function changeView(){
var region = document.getElementById('region').value;
$.ajax({
    type: 'GET',
    url: 'webservice.php',
    data: {region: region},
    success: function(response, textStatus, XMLHttpRequest) { 
        alert("SUCCESS");
        map.panTo(new L.LatLng(response[0].lat,response[0].lon));
    }
});
return false;
}
devShuba
  • 91
  • 3
  • 10
  • you need to stop the keydown event from propagating. once your onkeydown is done, the enter is still in the system, and will bubble upwards and submit the form. quick/dirty way is to simply do a `return false;` at the end of the onkeydown. – Marc B Apr 11 '13 at 18:32
  • Duplicate? http://stackoverflow.com/questions/895171/prevent-users-from-submitting-form-by-hitting-enter – George Apr 11 '13 at 18:35

2 Answers2

0

HTML:

<form action="webservice.php" method="post">
    <input type="text" value="London" name="region" id="region">
    <input type="submit" name="mySubmit" value="Search" >
</form>

Javascript:

$('#region').on('keydown', function(e) {
     if (e.which === 13) {
                $(this).parent('form').submit(); 
            }

    });


    $('.form').on('submit', function(e) {
        var self = $(this);

         $.ajax({
                type: self.attr('method') ,
                url: self.attr('action'),
                data: {region: $('#region').val()},
                success: function(response, textStatus, XMLHttpRequest) { 
                    alert("SUCCESS");
                    map.panTo(new L.LatLng(response[0].lat,response[0].lon));
                    }
            });
        e.PreventDefault();
        return false;
    });
fernandosavio
  • 9,849
  • 4
  • 24
  • 34
Imp0ssible
  • 49
  • 2
  • 8
-1

it looks like you're using jQuery, have you thought about just biding an event to the text box

something like this

$(document).ready(function(){ // binds when the document has finished loading
    $("#region").on('keypress', function(e){
        if (e.which === 13){  // enter key
            changeView();
        }
    });
});
jcolebrand
  • 15,889
  • 12
  • 75
  • 121
Kenneth Garza
  • 1,886
  • 14
  • 12