How can I use jQuery Autocomplete plugin for related input fields?

I am using jQuery Autocomplete plugin . I have two input fields on the form: inputfield1and inputfield2.

I attached autocomplete to the first field. When this field loses focus, I want to check if a value has been entered, and if so, then make an AJAX call to retrieve some "\ n" -separated strings and use them to drive autocomplete in the second field.

Below is the code I use for this:

/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>"); 

$("#inputfield1").blur(function(){

    // Attach autocomplete if inputfield1 field is not empty
    if($("#inputfield1").val() != ""){
        var url = "<url2>?q="+$("#inputfield1").val();
        $.get(url,function(data){
            result=data.split("\n");
            $("#inputfield2").autocomplete(result);

        });
    }
});

But the strange thing is: I can successfully attach autocomplete to the first field, but I need to focus twice on the second field in order to use autocomplete on it. Is there any way to fix this problem?

+3
4

. , , result , ( ). ( , ( , \t \r)), .

var data1 = ["a123", "b123", "c123", "d123", "e123", "f123", "g123", "h123", "i123", "j123",   "k123", "l123", "m123", "n123", "o123", "p123", "q123", "r123", "s123", "t123", "u123", "v123", "w123", "x123", "y123", "z123"];
var data2 = 'a123\nb123\nc123\nd123\ne123\nf123\ng123\nh123\ni123\nj123\nk123\nl123\nm123\nn123\no123\np123\nq123\nr123\ns123\nt123\nu123\nv123\nw123\nx123\ny123\nz123';
$("#inputfield1").autocomplete(data1);

$("#inputfield1").blur(function(){
    if($("#inputfield1").val() != ""){
        var result=data2.split("\n");
        $("#inputfield2").autocomplete(result);
    }
});
+1

, Autocomplete. 1.1, , , ( if ), , , ...

, , Autocomplete.

+1

:

.click(function(event) {
    $(target(event)).addClass(CLASSES.ACTIVE);
    select();
    // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
    input.focus();
    return false;

, . .

, blur(), , , result() .

/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>"); 

$("#inputfield1").result(function(event, data, formatted){

    // Attach autocomplete if inputfield1 field is not empty
    if(data){
        var url = "<url2>?q="+data;
        $.get(url,function(data1){
                result=data1.split("\n");
                $("#inputfield2").autocomplete(result);

        });
    }
});
+1

, # inputfield2, , ? . , , # inputfield2, , # inputfield2 ? , , # inputfield1 , "" (, - )?

, .

0

Source: https://habr.com/ru/post/1724592/


All Articles