I'm trying to use the autocomplete widget in jQuery however when I start typing nothing shows up below it. I can tell it's doing something becasue as I type I can see the scroll bar on the page changing as the list gets shorter, but I can't see the results. My code is below. Any help is appreciated with this.
My controller method looks like this:
public ActionResult GetUsers(string query)
{
var empName = from u in HomeModel.CombineNames()
where u.StartsWith(query)
select u.Distinct().ToArray();
return Json(empName);
}
My View looks like this:
<script type="text/javascript">
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: '/Home/GetUsers',
type: "POST",
dataType: "json",
data: { query: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value: item };
}));
}
});
}
});
})
</script>
<input type="text" id = "autocomplete"/>
You are missing a few things, like render item, cache managment.
the code should looks something like this: (assuming your action return an array of string)
var cache = {},lastXhr;
$( "input#autocomplete" ).autocomplete({
minLength: 4,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
var descripcion = new Array();
peticion = $.getJSON('/Home/GetUsers',{ query: request.term }, function (data, status, xhr) {
for (d in data) {
descripcion.push(data[d]);
}
cache[term] = descripcion;
if (xhr === peticion) {
response(descripcion);
}
});
},
select: function( event, ui ) {
$("input#autocomplete" ).val( ui.item);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item + " </a>" )
.appendTo( ul );
};
Try using the inspection tools of your browser to examine the area where your scroll bar is changing. If the elements are present, you likely need to make some changes to the CSS so your text color is different from the background color (or some other display-related issue).
Related
EDIT: The below code works, for anybody who would need!
This question is asked alot but couldn't find help for this specific one. I need to show a dropdown list that loads while I type in a search bar. While I type, I need to search in Active Directory for the Username that is being typed, and then it shows in the dropdown list all the options (say, it would only show results after 4 characters).
I have a simple form with one input, one button, a controller function to search user from a C# class that allows me to acces the AD. I put the JQuery script which retrieves data. The data is being correctly fetched but I cannot show it in the autocomplete. Any ideas?
The form:
<form class="form-inline" method="post" action="~/Home/SearchUserResult">
<label class="sr-only" for="inlineFormInput"> Nom et/ou Prénom </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom"/>
<button class="btn btn-primary" type="submit" id="searchValidate"> Rechercher </button>
</form>
My AD search function:
public List<string> SearchUserByName(string name)
{
try
{
SearchResultCollection resultCollection;
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(anr=" + name + ")";
search.PropertiesToLoad.Add("displayName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
lastName.Add(sResult.Properties["displayName"][0].ToString());
}
}
return lastName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
}
Here is the Controller function suggest by #caner
public ActionResult SearchUserByName(string name)
{
ADManager adManager = new ADManager();
List<string> lastName = adManager.SearchUserByName(name);
if (lastName != null)
{
ViewData["Names"] = lastName;
return Json(lastName,JsonRequestBehavior.AllowGet);
}
return null;
}
Finally here is the script I have for now, it gets the data but does not show it (in alert(data) I retrieve all the info I need):
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
Thanks for your help
EDIT: createDirectoryEntry() is a function I made just to create connection to AD.
EDIT 2 : If you have any other ideas to do that with something else than JQuery, I'm open to everything
Try jquery autocomplete like this...
your script:
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/YourController/SearchUserByName",
type: "POST",
data: { name: $("#searchName").val() },
dataType: "JSON",
success: function (data) {
response($.map(data.lastName, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
and your controller method:
public ActionResult SearchUserByName(string name)
{
.
.
.
return Json(lastName);
}
This script works for me:
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
I'm trying to use Select2 in Razor in ASP.NET MVC. But I can't get work.
$(document).ready(function () {
$(".genreOptions").select2({
tags: true,
ajax: {
url: 'http://localhost:65148/NewProfile/Genres',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id, //id part present in data
text: item.Genre //string to be displayed
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1
});
#Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { #class="genreOptions", multiple = "multiple", style ="width: 100%;"} )
The searching for tags works fine. But when I post the form, the count of the input field Is 0. How can I capture the data from the input form?
#Bryan I build up a javascript array and pass it with ajax to the server. Seems to work ok for my purposes. Perhaps you could try that. The selectors I put below will be different than what you need but here is the general idea...
On Click
$('#submitButton').click(function () {
fillHiddenInput();
var dataToSend = $('#hiddenInput').val();
//Submit the form with ajax or however you want to get dataToSend to server
});
FillHiddenInput function...
var fillHiddenInput = function () {
$('#hiddenInput').val("");
var stuff = [];
$('.ms-selection .ms-list li ul').children('li').each(function (){
if ($(this).hasClass('ms-selected'))
{
stuff.push($(this).children('span').text());
}
});
$('#hiddenInput').val(stuff);
}
I have a method in the controller that return a ViewBag with Json.
public JsonResult FilterCheck(int id, int[] mycheck, string idprot)
{
ViewBag.Utenti = this.GetDbContext().utente.Include(s => s.cod_servizio_utente).Where(x => x.cod_servizio_utente.Select(l => l.id).Contains(5)).ToList();
return Json(ViewBag.Utenti, JsonRequestBehavior.AllowGet);
}
In the view I have this script function ajax, if this function have "success" i would refresh a div that include a foreach on the viebag.Utenti:
$.ajax({
type: "POST",
url: "#Url.Action("FilterCheck","Operatore")",
datatype: "json",
traditional: true,
data: { 'mycheck': mycheck, 'idprot': idprot, 'id': '#Model.id' },
success: function(data) {
var html = $(data).filter('#external-events').html();
$('#external-events').html(data);
}
});
<div id='external-events'>
#foreach (HAnnoZero.Repositories.utente item in ViewBag.Utenti)
{
<div class='col-lg-3'><div class='external-event'>#item.id- #item.cognome #item.nome</div></div>
} </div>
But dont work. How can do for refresh the foreach inside div id "external events"?Who could help me?
Firstly you do not need to assign the collection to ViewBag
public ActionResult FilterCheck(int id, int[] mycheck, string idprot)
{
var data = this.GetDbContext().utente.Include(......
// Build anonymous object collection to avoid circular reference errors
var response = data.Select(d => new
{
id = d.id,
cognome = d.cognome
// other properties as required
});
return Json(response);
}
Secondly you are returning JSON, not html, so in your success function you need to iterate through the properties and build your html (not sure what your properties are, so adjust as necessary)
success: function(data) {
$('#external-events').empty(); // clear existing items
$.each(data, function(index, item) {
var div = $('<div><div>'); // Create new element
div.text(item.id + ' ' + item.cognome); // Set inner text
$('#external-events').append(div); // add the new element
});
}
An alternative is to have the action method return a partial view containing the html and then use
success: function(data) {
$('#external-events').html(data);
}
Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )
I am trying to
1) create a JQuery AutoComplete box that is populated from an aspx method, and
2)once I get the results, I wish to populate these results inside a list.
At the moment I am trying to do step one however without my success.
My code is as follows:-
ASPX
<script>
$(function () {
$("#persons").autocomplete({
//source: availableTags
source: function (request, response) {
var term = request.term;
var personArray = new Array();
$.post('JQAutoComplete.aspx/FetchPersonList', { personName: term }, function (persons) {
personArray = persons;
alert('PersonArray' - personArray);
alert('Persons' - persons);
response(personArray);
});
}
});
});
<div class="ui-widget">
<label for="persons">Persons: </label>
<input id="persons" />
</div>
</body>
and my aspx.cs is as follows :-
public JsonResult FetchPersonList(string personName)
{
var persons = ctx.GetDataFromXML(false, 0);
return (persons) as JsonResult;
}
*************UPDATE ASPX.CS*******************
ok so I changed the method to this:-
[WebMethod]
public static List<Person> FetchPersonList()
{
//var persons = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>) persons;
}
but I am still not getting through the method!
However the code is not hitting this method at all.
How can I get this list?
Thanks for your help and time
Ok I found the problem.
I changed my JQuery to the following and its calling the method now :-
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#persons").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JQAutoComplete2.aspx/FetchPersons",
data: "{'name':'" + document.getElementById('persons').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
alert(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and my ASPX.CS looks like this :-
[WebMethod]
public static List<Person> FetchPersons(string name)
{
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>)persons;
}