I wish to do the same thing as this tutorial here but instead of populate every field separately, I wish when I select the first name, the other fields autofill according to the selected value of first name
from database.
Set an event listener on one of the name filelds, which contains one of the names. Call a function to populate the input fields. I hope you 'll find it useful
See code below:
<form>
<input
type="text"
name="first_name"
id="first_name"
placeholder="First Name"
/>
<input
type="text"
name="last_name"
id="last_name"
placeholder="Last Name"
/>
</form>
<script>
//This comes from the ajax request:
var namesFromDB = ["John Doe", "Ferenc Minta", "Dr. Heinz Doofenshmirtz"];
//Var init:
var firstNames = {};
var lastNames = {};
//When the doc loads
$(function () {
//Loop over the names to split them by whitespace
$.each(namesFromDB, function (index, val) {
let nameSplit = val.split(" ");
//To handle the names or pronunciations. You can extend this further more.
switch (nameSplit.length) {
case 3:
firstNames[index] = nameSplit[0] + " " + nameSplit[1];
lastNames[index] = nameSplit[2];
break;
case 4:
firstNames[index] =
nameSplit[0] + " " + nameSplit[1] + " " + nameSplit[2];
lastNames[index] = nameSplit[3];
break;
default:
firstNames[index] = nameSplit[0];
lastNames[index] = nameSplit[1];
break;
}
});
//The change event listeners:
//When the user click away from the input, and it lost its focus, this event handler will trigger and sets the other input field:
$("#first_name").on("change", function (e) {
let fVal = $("#first_name").val();
let fKey = Object.keys(firstNames).find((k) => firstNames[k] === fVal);
$("#last_name").val(lastNames[fKey]);
});
//It's the same, you can improve this by making a function for it (sry, im lazy):
$("#last_name").on("change", function () {
let lVal = $("#last_name").val();
let lKey = Object.keys(lastNames).find((k) => lastNames[k] === lVal);
$("#first_name").val(firstNames[lKey]);
});
//Source declaration for the datas. Because we use objects in this case, we need only the values.
$("#first_name").autocomplete({
source: Object.values(firstNames),
});
$("#last_name").autocomplete({
source: Object.values(lastNames),
});
});
</script>