@
@
@pustbay2021-01-31 23:10:23
JavaScript
@pustbay, 2021-01-31 23:10:23

How to solve problem with Jquery Autocomplete when filling multiple fields?

You need to make a script autocomplete the input fields when the user enters an address.

To do this, I wrote a php script that, using the REST API of the Ahunter.ru service ( ahunter.ru/site/doc/api/suggest/address ), collects hints for the address entered by the user, processes them and forms an array in JSON format, for its subsequent processing by Jquery Autocomplete

Problems arose while writing a Jquery script for an ajax request to a php script. jquery script code:


<script type="text/javascript">
 
 $('.address').each(function(){
 
$(this).autocomplete({ source: function(request,response) {
  
 var val =  $('.address').val();
 
        	
  $.getJSON('http://doc.army-help.ru/files/1.php?query=' + val,  function(data){
     	
    	var suggestions = []; // массив для хранения результатов
    	$.each(data, function(key, val) {
                 	
            	suggestions.push(val.value); // добавляем все элементы
        	});
            response(suggestions);
    	});
        	
  } 	
});
 
 
});
 
</script>


The script works, but the problem is that the .each function is used to process multiple address fields on the page. In this case, all fields are processed, but the data for the val variable (the data entered by the user is placed in it) are taken only from the 1st address class in order.

!!! QUESTION:

I do not understand how to fill the val variable with the content of exactly the input that the user fills. Tried options - var val = $(this).val(); and varval = this.value; but they don't work.

PHP script address - doc.army-help.ru/files/1.php?query=%D0%BD%D0%B8%D0...

Page address with ajax script - doc.army-help.ru/files /2.php

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lamer350, 2021-01-31
_

In this case, it is wrong to bypass all fields, each is not a helper here.
It will correctly track the data entered in the field and immediately process the data from it

$('body').on('keyup', '.address', function(){
 var item = $(this);
item.autocomplete({ source: function(request,response) {
 var val = item.val();
 $.getJSON('http://doc.army-help.ru/files/1.php?query=' + val,  function(data){
     	
    	var suggestions = []; // массив для хранения результатов
    	$.each(data, function(key, val) {
                 	
            	suggestions.push(val.value); // добавляем все элементы
        	});
            response(suggestions);
    	});
        	
  } 	
});
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question