Javascript Autocomplete Inputfield Variables

Viewed 73

how can I use a value of an autocomplete inputfield in a second-inputfield?

I wrote this script below but I dont know how to use the variables from the first in the second-inputfield? the first-field responses: [{"label":"TEST","value":1}] and i need the "value" for the second field..



$(document).ready(function(){
  
  jQuery('#first-field').autocomplete({
        source:'',
        minLength: 2,
        delay:0,
        select: function(event, ui) {
                event.preventDefault();
                $("first-field").val(ui.item.label);              
        },
        focus: function(event, ui) {
                event.preventDefault();
                $("#first-field").val(ui.item.label);
        }
    });
    
       jQuery('#second-field').autocomplete({
        source:'',
        minLength: 2,
        delay:0,
        select: function(event, ui) {
                event.preventDefault();
                $("second-field").val(ui.item.label);            
        },
        focus: function(event, ui) {
                event.preventDefault();
                $("#second-field").val(ui.item.label);
        }
    });      
});

1 Answers

Try This

<label for="FirstField">First Name</label> <input id="FirstField" />
<br />
<br />
<label for="SecondField">Second Name</label> <input id="SecondField" />

$(function() {
    $('#FirstField, #SecondField').autocomplete({
        source: [
              "Some Name",
              "Value",
              "Place"
           ],
        minLength: 0,
        select: function( event, ui ) {
    
            $('#SecondField').val(ui.item.value);
            $('#FirstField').val(ui.item.value);
            return false;
        }
    })
    .focus(function()
    {
  var self = this;

  window.setTimeout(function()
  {
    if (self.value.length == 0)
      $(self).autocomplete('search', '');
  });
        
})
    
$('#FirstField').change(function() {
$('#SecondField').val($(this).val());
});
    
}); 
Related