I am trying to use jquery-ui's autocomplete to add a suffix of email domain (Eg. @gmail.com, @yahoo.com) to the existing value of a text field, when it is focused.
The following is my code:
$('body').on('focusin', '#id_email', function () {
console.log("Focused")
$('#id_email').autocomplete({
minLength: 0,
autoFocus: true,
source: ["@gmail.com", "@yahoo.com", "@yahoo.co.in", "@hotmail.com", "@live.com"],
select: function (event, ui) {
var suffix = ui.item.value;
existing_val = $("#id_email").val();
new_val = existing_val + suffix;
console.log(`Existing value"${existing_val} Suffix: ${suffix} New value:${new_val}`);
$("#id_email").val(new_val);
}
}).focus(function () {
$(this).autocomplete("search", "");
})
});
The problem is that even though I have code for setting a new value for the text field on selecting one of the autocomplete options, the selected value replaces the field's existing value. Output in console:
Existing value"joelg@ Suffix: @gmail.com New value:joelg@@gmail.com
According to the output, the new value of the text field should be joelg@@gmail.com. However what actually happens is that even though the text field initially contained an initial value of joelg@, on focusing the field, the autocomplete menu is shown, and on selecting "@gmail.com", the existing value is replaced by "@gmail.com", instead of the input field getting a value of joelg@@gmail.com.