按enter键时使用Javascript

Use Javascript when pressing enter

本文关键字:Javascript enter      更新时间:2023-09-26

我想在输入字段中按enter键时调用一个函数。问题是,它只是重新加载页面的时刻,而不调用JavaScript。当我按下按钮时,JavaScript工作没有任何问题。现在我想要得到相同的结果,当我按回车键时。

这是我的表格

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

我也试着把它放入文本字段onKeydown="Javascript: if (event.keyCode==13) changeView();

但它并没有真正帮助。这是我的JavaScript函数

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;
}

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;
    });

看起来你是在使用jQuery,你有没有想过将事件绑定到文本框

像这样的

$(document).ready(function(){ // binds when the document has finished loading
    $("#region").on('keypress', function(e){
        if (e.which === 13){  // enter key
            changeView();
        }
    });
});