Home > OS >  Javascript autocomplete with different input field value
Javascript autocomplete with different input field value

Time:01-31

I have the following javascript that autocompletes based on a users display name. Problem is that the autocomplete input field is the display name. Each user actually has a user id, but I want to look up the user in the autocomplete based on the display name but when I submit the form I want to submit the user ID itself.

<script>

$(document).ready(function() {
$("input#autocomplete").autocomplete({

source: [
"John Doe", 
"Another User", 

]

});

});

</script>

<input id="autocomplete" name="autocomplete"/>

Can anyone suggest how i can do this? Ideally in the source, is there a way to have the user ID as the value too and somehow have the user ID submitted but with display name?

CodePudding user response:

instead of using just an array you could use object inside the array so you can still do your search for matching display name and return the user id

instead of:

source: [
"John Doe", 
"Another User", 

]

you can do:

var sourceValues = [
    {label: "John Doe",          value: 1},
    {label: "Another User",        value: 2},
]

$("#autocomplete").autocomplete({
    source: sourceValues.map(lang=>lang.label),
});

CodePudding user response:

Consider the following example.

$(function() {
  $("#user_name").autocomplete({
    source: [{
      label: "John Doe",
      value: 1001
    }, {
      label: "Jonny Appleseed",
      value: 1002
    },{
      label: "Jane Doe",
      value: 1003
    }],
    select: function(e, ui) {
      $("#user_name").val(ui.item.label);
      $("#user_id").val(ui.item.value);
      return false;
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<div>Name: <input id="user_name" /></div>
<div>ID: <input type="text" id="user_id" /></div>

This is based on this example: https://jqueryui.com/autocomplete/#custom-data

If you define a more complex source, you can make use of it in the select callback. ui.item represents the object selected. It has a label and value that you can put in various fields.

  •  Tags:  
  • Related