我有一个自动完成函数,其中的表单中键入了城市的名称。所有可能的值都在数据库中,并从数据库中提取,并将其存储在变量$list 中
然后我有了带有输入和按钮的表格
<form name="form1" method="post" action="searchresults.php" >
<input id="hero-demo" autofocus type="search" name="search" placeholder="City" >
<input type="submit" name="submit" value="Search">
</form>
以及自动完成功能:
<script>
$(function(){
$('#hero-demo').autoComplete({
minChars: 1,
source: function(term, suggest){
term = term.toLowerCase();
var choices = [<?= $list ?>];
var suggestions = [];
for (i=0;i<choices.length;i++)
if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
suggest(suggestions);
}
});
});
</script>
我该怎么做呢?例如,如果用户引入了值"London",而该值不在我的数据库($list)中,那么"搜索"按钮就不起作用。
非常感谢
您可以在js代码中添加submit
事件,然后在提交表单之前执行您想要的操作,在这种情况下,您应该从HTML代码中删除内联事件。
HTML:
<form name="form1" method="post" action="searchresults.php" >
JS:
$('form[name="form1"]').on('submit', function(e){
//Prevent form submiting after click on submit button
e.preventDefault();
//Do what you want
$('#hero-demo').blur();
//Submit the form
$(this).submit();
});
希望这能有所帮助。