JQuery 自动完成:在选择时提交表单? [英] JQuery Autocomplete: Submit Form on selection?

查看:28
本文介绍了JQuery 自动完成:在选择时提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传统 HTML 表单上使用 JQuery 自动完成.

Using JQuery Autocomplete on a traditional HTML form.

尝试在做出选择时提交表单(老式方式).

Trying submit the form (the old-fashioned way) when a selection is made.

但是输入框被填满了,然后我必须第二次按返回",或者点击提交按钮.

But the input box gets filled out and then I have to make press "return" a 2nd time, or click the submit button.

我已经尝试了一些 SO 示例,但我无法让它们工作.

I've tried a few SO examples, but I could not get them to work.

选择后如何自动提交表单?

How do you submit the form automatically when the selection is made?

推荐答案

更新: 我终于想通了这一点,下面的代码应该可以解决问题.由于某种原因,change 回调不起作用,但是 close &select 回调做.使用 select 更好,因为如果字段失去焦点,也会调用 close.

UPDATE: I finally figured this one out, the code below should do the trick. For some reason the change callback was not working, but the close & select callbacks do. Using select is better, since close will also be called if the field loses focus.

$(function() {
    $("#searchField").autocomplete({
        source: "values.json",
        select: function(event, ui) { 
            $("#searchForm").submit(); }
    });
});

另一个更新:好吧,select 回调也有问题,这是默认情况下(在上面的代码中),如果你用键盘,并用回车键选择,在提交表单之前更改输入.但是,如果您用鼠标选择它,表单会在输入更改之前提交,因此提交的值就是用户键入的值(而不是她从自动完成下拉列表中选择的值).似乎有效的解决方法是:

ANOTHER UPDATE: Ok, there's also a problem with the select callback, which is that by default (in the code above) if you traverse the autocomplete drop down with the keyboard, and select with the enter key, the input is changed before the form is submitted. However, if you select it with the mouse, the form is submitted just before the input is changed, so the value submitted is just what the user typed (not what she selected from the autocomplete dropdown). The woraround that seems to work is:

$("#searchField").autocomplete({
    source: "values.json",
    minLength: 2,
    select: function(event, ui) { 
        $("#searchField").val(ui.item.label);
        $("#searchForm").submit(); }
});

这篇关于JQuery 自动完成:在选择时提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆