nonstop328 nonstop328 - 23 days ago 7
Javascript Question

how to remove specific character and text

I have finish autocomplete with a jquery library which is


using jquery-ui-1.12.1.min.js


. I have modified it to make to get the search with username and full name. it will show as below image

enter image description here

when I select the value it will paste the whole text into an input box.

enter image description here

here is my question how do it modify it to show as the image but when I select the value it will only paste the username into input box?

how i only want nonstop00000 paste it into input box when i select the 1st value

here is my javascript

$(document).ready(function () {
$("#id").autocomplete({
source: function(request,response) {
$.ajax({
url: '@Url.Content("~/UserManagement/AutoCompleteUser")/',
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return [{ label: item.Username + " | " + item.FullName, value: item.id }];
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})


here is my search controller

if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Username.Trim().Contains(searchString.Trim())
|| s.FullName.Trim().Contains(searchString.Trim()));
}


here is my autocomplete controller

public JsonResult AutoCompleteUser(string term)
{
var result = (from r in db.UserTables
where ((r.Status == "Active") && (r.Username.ToLower().Contains(term.ToLower()) || (r.FullName.ToLower().Contains(term.ToLower()))))
select new { Username = r.Username, FullName = r.FullName }).Distinct();
return Json(result);
}


here is my view

<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12 search-panel">
@using (Html.BeginForm("Index", "UserManagement", FormMethod.Get))
{
<div class="input-group form-group ui-widget">
@Html.TextBox("id", ViewBag.CurrentFilter as string, new { @class = "form-control autocomplete", @placeholder = "Search for..." })
<span class="input-group-btn">
<input type="submit" value="Search" class="form-control autocomplete " />
</span>
</div>
}
</div>

Answer

To achieve this you can use the select event to amend the value to be placed in to the input. Try this:

$("#id").autocomplete({
    // your settings...
    select: function(e, ui) {
        e.preventDefault();
        $('#id').val(ui.item.label.split('|')[0].trim());
    }
});