how to remove specific character and text - javascript

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
when I select the value it will paste the whole text into an input box.
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>

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());
}
});

Related

stopping the no results label being added to input and if input matches a label

I have created an autocomplete input, it works well but i want to expand it and make it better. But this is a struggle with my limited jquery ui knowledge and despite some trial and error i cannot seem to work out two problems.
The first problem i would like to address is making the noresult label not selectable meaning that it can't be added to the input on focus or on select or at all.
I want to make it so that if what the user has entered into the input box matched the label value but they did not select it for some reason then when they press the submit button on my form the label that is a match is selected and therefore inputted.
Here is what i have so far:
html:
<div class="search-homepage-input">
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9 col-l">
{!! Form::text('sl', null, array('class' => 'form-control shop-input', 'maxlength' =>'50', 'placeholder' => 'Search by city. Eg. London, New York, Paris...', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3 col-r">
{!! Form::submit('Find Shops', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
</div>
PHP laravel:
public function autoComplete(Request $request){
$query = $request->term;
$res = City::where('name', 'LIKE', "%$query%")->orderBy('name')->paginate(5);
foreach($res as $cities ){
$usersArray[] = array(
"label" => $cities->name,
"value" => $cities->id,
"country" => $cities->countries->id,
"countryname" => $cities->countries->country
);
}
return response()->json($usersArray);
}
JS:
$('#sl').autocomplete({
source: '/autocomplete',
select: function(event, ui) {
event.preventDefault();
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label +', '+ ui.item.countryname)
},
focus: function(event, ui){
event.preventDefault();
$('#sl').val(ui.item.label+', '+ui.item.countryname);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = { value:"",label:'No results found', countryname:"" };
ui.content.push(noResult);
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
var li = $("<li>");
if (item.country == undefined) {
li.append("<div>" + item.label +"</div>");
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
};
An example of how to disable a selection item is found here: http://jqueryui.com/autocomplete/#categories
This example is a bit complex, since we're accessing the menu widget inside the autocomplete widget. For your code, a similar method can be used:
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
widget()
Returns a jQuery object containing the menu element. Although the menu items are constantly created and destroyed, the menu element itself is created during initialization and is constantly reused.
This addresses point #1.
To address point #2, you need to consider the logic of assuming a selection if the user has not made a selection. For example, if the user typed in l and got 10 results, or even just 2 results... which do you select for the user? Also, if the user has navigated away from the field, autoselect would close it's menu and destroy the results.
In my opinion, it would be better to examine the hidden fields, if they are empty, prevent the form from being submitted and force the user to select an option, make it a required field.
$(function() {
var countries = [{
country: 1,
countryname: "UK",
label: "London",
value: 1
}, {
country: 1,
countryname: "UK",
label: "Manchester",
value: 2
}];
$('#sl').autocomplete({
source: countries,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label === "No results found") {
$("#sl").val("");
return false;
}
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label + ', ' + ui.item.countryname)
},
focus: function(event, ui) {
event.preventDefault();
$('#sl').val(ui.item.label);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: 'No results found'
};
ui.content.push(noResult);
}
}
});
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
$("#sl").autocomplete("instance")._renderItem = function(ul, item) {
var li = $("<li>");
if (item.country == undefined) {
li.addClass("no-select").append(item.label);
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
}
$("form").submit(function(e) {
e.preventDefault();
console.log($(this).serialize());
if ($("#country").val() == "" || $("#city").val() == "") {
$("#sl").focus();
return false;
}
return true;
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="search-homepage-input">
<form>
<div class="col-md-9">
<input type="text" name="sl" class="form-control shop-input" max-length="50" placeholder="Eg. England, London, Manchester" id="sl" /> <span style="color: red; font-size: 65%;">* Required</span>
<input type="text" name="country" id="country" style="display: none;" />
<input type="text" name="city" id="city" style="display: none;" />
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-homepage">Find Teams</button>
</div>
</form>
</div>
Hope that helps.

Kendo UI javascript : remote bind form

I'm having trouble getting started with binding a Form to a remote Datasource in Kendo UI for javascript
I have verified that the ajax call returns the correct JSONP payload, e.g:
jQuery31006691693527470279_1519697653511([{"employee_id":1,"username":"Chai"}])
Below is the code:
<script type="text/javascript">
$(document).ready(function() {
var viewModel = kendo.observable({
employeeSource: new kendo.data.DataSource({
transport: {
read: {
url: baseUrl + "/temp1",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "employee_id",
fields:{
employee_id: { type: "number" },
username: { type: "string" }
}
}
}
}),
hasChanges: false,
save: function() {
this.employeeSource.sync();
this.set("hasChanges", false);
},
change: function() {
this.set("hasChanges", true);
}
});
kendo.bind($("#item-container"), viewModel);
viewModel.employeeSource.read();
});
</script>
<div id="item-container">
<div class="row">
<div class="col-xs-6 form-group">
<label>Username</label>
<input class="form-control k-textbox" type="text" id="username" data-bind="value: username, events: { change: change }" />
</div>
</div>
<button data-bind="click: save, enabled: hasChanges" class="k-button k-primary">Submit All Changes</button>
</div>
No errors are thrown, but I was expecting my username text form field to be populated with the value 'Chai', and so on.. but it doesn't
Your textbox is bound to a username property but this doesn't exist on your view-model, nor is it being populated anywhere. Assuming your datasource correctly holds an employee after your call to read(), you will need to extract it and set it into your viewmodel using something like this:
change: function(e) {
var data = this.data();
if (data.length && data.length === 1) {
this.set("employee", data[0]);
this.set("hasChanges", true);
}
}
And modify the binding(s) like this:
<input class="form-control k-textbox" type="text" id="username"
data-bind="value: employee.username, events: { change: change }" />
You should also be aware that the change event is raised in other situations, so if you start using the datasource to make updates for example, you'll need to adapt that code to take account of the type of request. See the event documentation for more info. Hope this helps.

search kendo multiselect without adding values to multiselect

Background: I have a kendo multiselect that gets populated with emails based on the values of a kendo dropdown. I also need to use the multiselect to 'search' for additional emails through our employee api. Then as i search and select new values to be added to the 'selected values' portion of the multiselect i want to be able to go back and see the initial populated values without the searched values.
Disclaimer: I can get all of this to work except the searched values get 'added' to the datasource which I dont want. Think of a temporary datasource when searching. So when i go to look through the initial populated values, the returned search vales are appended to the datasource values. Again, I do not want this.
CODE:
<div class="row display-row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<h4>Location Group:</h4>
#(Html.Kendo().DropDownList()
.Name("weatherLocGroupNameDropDown")
.HtmlAttributes(new { style = "width:100%" })
.OptionLabel("Select location group...")
.DataTextField("LocationGroupName")
.DataValueField("LocationGroupId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getLocationGroupNames", "Base");
});
})
)
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<h4>Location:</h4>
#(Html.Kendo().DropDownList()
.Name("weatherLocNameDropDown")
.HtmlAttributes(new { style = "width:100%" })
.OptionLabel("Select location...")
.DataTextField("LocationName")
.DataValueField("LocationId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getLocationNamesFilteredByLocationGroup", "Base")
.Data("filterLocation");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.Events(ev => ev.Change("populateLocGrpEmails"))
.CascadeFrom("weatherLocGroupNameDropDown")
)
</div>
<div class="row display-row">
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
#(Html.Kendo().MultiSelect()
.Name("recipientMultilist")
.Placeholder("Recipient(s)")
.AutoBind(false)
.Enable(false)
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("EmailName")
.DataValueField("EmailId")
.Events(ev => ev.Filtering("searchEmails"))
)
</div>
</div>
function searchEmails() {
var searchText = $("#recipientMultilist").data('kendoMultiSelect').input.val();
searchText = searchText.trim();
if (searchText.length >= 3 && searchText != undefined && searchText != "") {
$.ajax(
{
url: "#Url.Action("getRecipientEmails", "Base")",
data: { searchTerm: searchText },
type: "GET",
dataType: "json",
async: false,
success: function (searchEmail) {
if (searchEmail.length > 0) {
for (var i = 0; i < searchEmail.length; i++) {
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: searchEmail[i].EmailName,
EmailId: searchEmail[i].EmailId
});
}
}
}, error: function (searchEmailErr) { console.log('searchEmailErr: ', searchEmailErr); }
})
}
}
function getLocationGroupEmails() {
return {
LocationGroupId: $("#weatherLocGroupNameDropDown").data("kendoDropDownList").value()
}
}
function filterLocation() {
return {
LocationGroupId: $("#weatherLocGroupNameDropDown").data("kendoDropDownList").value()
};
}
function populateLocGrpEmails() {
$("#recipientMultilist").data("kendoMultiSelect").enable();
tempMultiListStorage = [];
var locationText = $("#weatherLocNameDropDown").data('kendoDropDownList').text();
var locationGroupId = $("#weatherLocGroupNameDropDown").data('kendoDropDownList').value()
//get all emails associated with the location group and inserts into the recipientMultilist
$.ajax(
{
url: "#Url.Action("getEmailFilteredByLocationGroup", "Base")",
data: { LocationName: locationText, LocationGroupId: locationGroupId },
type: "GET",
dataType: "json",
async: false,
success: function (filteredEmail) {
if (filteredEmail.length > 0) {
for (var i = 0; i < filteredEmail.length; i++) {
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: filteredEmail[i].EmailName,
EmailId: filteredEmail[i].EmailId
});
tempMultiListStorage.push({
EmailName: filteredEmail[i].EmailName,
EmailId: filteredEmail[i].EmailId })
}
}
}, error: function (filteredEmailErr) { console.log('filteredEmailErr: ', filteredEmailErr); }
})
var multiselect = tempMultiListStorage
//"selects" the record that matches the location
var dropdownlist = $("#recipientMultilist").getKendoMultiSelect();
dropdownlist.value(locationText)
dropdownlist.trigger("change");
}
I do know that this code in searchEmails
$('#recipientMultilist').data("kendoMultiSelect").dataSource.add({
EmailName: searchEmail[i].EmailName,
EmailId: searchEmail[i].EmailId
});
is adding the values to the multiselect but thats there so i can at least test a few other things. Again, i am looking to 'see' the searched values, select the search values but not make them part of the 'datasource' by adding them.
I hope this was clear haha.
Can you give this a try and see if it works:
$("#multiselect").kendoMultiSelect({
select: function(e) {
e.preventDefault();
}
});

Semantic ui search not work

I work with semantic ui and when I do a search on a website the result is empty but when I look at my console I see the json result
this is my js code
$('.ui.search').search({
apiSettings: {
url: "https://api.github.com/search/repositories?q={query}"
},
fields: {
results: 'items',
title: 'name',
url: 'html_url',
description: 'description'
}
});
and my html code
<div class="ui right aligned category search item">
<div class="ui transparent icon input">
<input class="prompt" placeholder="Rechercher" type="text">
<i class="search link icon"></i>
</div>
<div class="results"></div>
</div>
screenshot results in my html page
and i have try the exemple for semantic-ui page
$('.ui.search')
.search({
type : 'category',
minCharacters : 3,
apiSettings : {
onResponse: function(githubResponse) {
var
response = {
results : {}
}
;
// translate GitHub API response to work with search
$.each(githubResponse.items, function(index, item) {
var
language = item.language || 'Unknown',
maxResults = 8
;
if(index >= maxResults) {
return false;
}
// create new language category
if(response.results[language] === undefined) {
response.results[language] = {
name : language,
results : []
};
}
// add result to category
response.results[language].results.push({
title : item.name,
description : item.description,
url : item.html_url
});
});
return response;
},
url: '//api.github.com/search/repositories?q={query}'
}
})
and this is not work
have the same problem as you
debugger and get this:
debug screenshot
it seems will get 'results' field from response, so if your response without 'results' field you need set 'results' in onResponse callback:
apiSettings : {
onResponse (response) {
return {
results: response.myresults
}
}
}
and if you didn't set the templates, it will use the standard template, standard template use 'title' field to show, you need do some transform like this:
response.myresults.forEach((item) => {
item.title = item.name;
})
hope this can help you

How to do autocomplete using values from the database in MVC 5?

At the moment, I have the following code:
main.js:
$(function () {
var keys = ["test1", "test2", "test3", "test4"];
$("#keywords-manual").autocomplete({
minLength: 2,
source: keys
});
});
Test.cshtml:
#model App.Models.Service
#{
ViewBag.Title = "Test";
}
<script src="~/Scripts/main.js"></script>
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
#using (Html.BeginForm("SaveAndShare", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<h4>Create a new request.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.ServiceType, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ServiceType, new { #class = "form-control", #id = "keywords-manual" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit!" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The point is that currently I have just provided 4 constant values to the autocomplete. But then I created a database and a table named "services", which comes from my model named Service. I have already provided a few rows to the table with values. I have a field in my table called ServiceType, and I want the autocomplete to take the values of that column as a source. Please note that I have hosted my database in Azure and it is MySQL, though, I think it doesn't matter here. Can you tell me how can I take as a source the values of ServiceType column that is located inside my services table?
As far as I can tell by your question, it should look something like this:
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetServiceTypes",
data: "{ 'keywords': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id
}
}))
}
});
},
minLength: 2
});
And the controller,
YourContext db = new YourContext();
public JsonResult GetServiceTypes() {
db.ServiceType.Where(s => keywords == null || s.Name.ToLower()
.Contains(keywords.ToLower()))
.Select(x => new { id = x.ServiceTypeID, value = x.ServiceTypeName }).Take(5).ToList();
return result;
}
Apologies for any typos, but that should be the jist of it. If you need to be searching for more than one keyword, in the controller method, split the value from 'keywords-manual' into a string array, then use a foreach loop or similar approach to match each value, adding matches to a total list each time.
** I say string array, that's pretty oldschool, split it into a list :)

Categories