简体   繁体   English

在错误的表单字段上自动完成

[英]Autocomplete on wrong form field

I know some php/html/css but javascript is where I need help. 我知道一些php / html / css,但是javascript是我需要帮助的地方。 I found on web autocomplete script, but this doesn't work on more than two input fields. 我在网络上自动完成脚本中找到了,但这不适用于两个以上的输入字段。

There are two problems I need to solve. 我需要解决两个问题。

  1. When you type in first box, autocomplete shows in second one. 当您在第一个框中键入内容时,第二个将显示自动完成功能。 How to make script show autocomplete on box where user is typing? 如何使脚本在用户键入的框中显示自动完成功能?

  2. I need to use the same autocomplete on multiple fields on my site. 我需要在网站上的多个字段上使用相同的自动完成功能。

The javascript syntax I use is: 我使用的javascript语法是:

var MIN_LENGTH = 2;

$( document ).ready(function() {
$("#keyword").keyup(function() {
    var keyword = $("#keyword").val();
    if (keyword.length >= MIN_LENGTH) {

        $.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
        .done(function( data ) {
            $('#results').html('');
            var results = jQuery.parseJSON(data);
            $(results).each(function(key, value) {
                $('#results').append('<div class="item">' + value + '</div>');
            })

            $('.item').click(function() {
                var text = $(this).html();
                $('#keyword').val(text);
            })

        });
    } else {
        $('#results').html('');
    }
});

$("#keyword").blur(function(){
        $("#results").fadeOut(500);
    })
    .focus(function() {     
        $("#results").show();
    });

});

In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element. 为了重复使用相同的自动完成代码,您需要为函数范围提供正确的DOM元素的上下文。

Here's aa quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures. 这是带有一些简单HTML代码的快速jsfiddle,但它应该提供一个基本示例,说明如何将相同事件绑定到多个dom结构。

DEMO: JSfiddle example 演示:JSfiddle示例

JS JS

var MIN_LENGTH = 2;

$(document).ready(function() {

  $(".keyword").keyup(function() {

    var $parent = $(this).parent();
    var $results = $parent.find('.results');
    var keyword = $(this).val();

    if (keyword.length >= MIN_LENGTH) {

      $.get("/echo/json/", {
          keyword: keyword
        })
        .done(function(data) {

          $results.html('');
          data = ['test', 'test2'];
          //data = jQuery.parseJSON(data);
          $(data).each(function(key, value) {
            $results.append('<div class="item">' + value + '</div>');
          });

        });
    } else {
      $results.html('');
    }
  });

});

HTML 的HTML

<div class="autcomplete">
  <input class="keyword" /> 
  <ul class="results"></ul>
</div>

<div class="autcomplete">
  <input class="keyword" /> 
  <ul class="results"></ul>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM