如何在使用鼠标从下拉列表中选择值后,在输入框中保持焦点



我有一个输入框,它依赖于Google API根据用户类型建议城市/州组合。当用户用鼠标从可能选项的下拉列表中选择谷歌建议的城市/州组合时(如果用户使用上/下箭头键进行选择,则不存在此问题(,由于某种原因,输入框会失去焦点。在用户使用鼠标从谷歌下拉列表中选择正确的值后,我们如何确保输入框保持焦点?这是我的html代码:

<div class="col-md-4 col-sm-12 col-xs-12">
<div class="form-group">
<input gp-gac="{ types: ['(cities)'],  componentRestrictions: { country: 'US' }}" class="form-control"
ng-model="home_ctrl.location"
gp-components="{ locality: 'long_name', administrative_area_level_1: 'short_name' }"
gp-callback="home_ctrl.gpSearchCb(result, place)"
vs-city="home_ctrl.city"
vs-state="home_ctrl.state"
placeholder="City, State"
id="txtCity">
</div>
</div>

我试图在输入标签中包含一个onclick事件

onclick = "putFocus()"

它引用了我的javascript代码中的以下函数:

function putFocus(){
document.getElementByd("txtCity").focus()
}

但这似乎也没有奏效。感谢您的帮助。

我建议您创建一个自定义的CSS类,其中包含您希望在"聚焦"时向用户显示输入的方式,并在用户单击时将其添加到您的输入中。.focus不会起作用,因为当输入处于聚焦状态时,它被"选中",这意味着光标在输入元素内。

试试这样的东西:

<!DOCTYPE html>
<html>
<style>
.focused{
border-style: solid, 10px;
border-color: blue;
}
</style>
<body>
<input type="text" id="myInput" onClick="myFunction()">
<script>
function myFunction() {
myInput = document.getElementById("myInput");
myInput.classList.add("focused");
}
</script>
</body>
</html>

想清楚。我所要做的就是在homeController.js文件中的gpSearchCb函数的末尾添加以下行:

$('#txtCity').focus()

并且在用鼠标进行选择之后将焦点保持在正确的输入字段中。

最新更新