Jquery UI 自动完成在按下 Enter 后不会提交

Jquery UI autocomplete doesn't submit after Enter is pressed

本文关键字:Enter 提交 UI Jquery      更新时间:2023-09-26

我正在处理一个简单的搜索框,用户可以在其中键入值或从下拉菜单中选择它。现在,当您从菜单中选择时,它可以正常工作,但是如果您按Enter键,它不会执行任何操作。任何帮助,不胜感激。谢谢

var source = [ { value: "src/devices/consoles/ps4.php",
                 label:"PlayStation 4"
               },
               { value: "src/devices/consoles/ps4.php",
                 label:"PS4"
               },
               { value: "src/devices/consoles/ps4.php",
                 label:"Sony"
               },
                { value: "src/devices/consoles/xbox.php",
                 label:"Xbox One"
               },
               { value: "src/devices/consoles/xbox.php",
                 label:"Microsoft"
               },
                { value: "src/devices/consoles/wiu.php",
                 label:"Nintendo"
              },
              { value: "src/devices/consoles/wiu.php",
                 label:"Wii U"
               }
             ];
    $("input#tags").autocomplete({
        source: source,
        select: function( event, ui ) { 
            window.location.href = ui.item.value;
        }
    });

在事件处理程序中,尝试添加val()属性,并说明应允许在表示 Enter 的keyCode 13上提交:

    // ...
    select: function (event, ui) {
        window.location.href = ui.item.value;
        $(this).val(ui.item.value).val();
        if (event.keyCode == 13) {
            $("#id_of_button").submit();
        }
    }
    // ...

或者在事件处理程序中使用另一种方式,定义按下键键以输入并触发单击:

    // ...
    select: function (event, ui) {
        window.location.href = ui.item.value;
        var e = jQuery.Event("keydown");
         e.which = 13;
         $("id_of_button").trigger(e);
    }
    // ...

试试这个:

$("#inputbox").on("keypress", function(e) {
    if (e.which == 13) {
        $("#submitbutton").click();
        // or $("form").submit();
    }
});

资源:

  • .submit()
  • .keypress()