.keyup event alternative
Asked Answered
G

4

0

I have a simple autocomplete test which works with hard coded data.

However when i add my own data (which contains over 1000 data) it doesn't work and only shows the first letter, so if my data is "Apple"

when i type B - it shows Banana but i cannot type "BA" as the "A" disappears.

I was expecting that i can write the whole word rather than the first letter.

This is the working code:

 var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";

$('#ac').autocomplete({
autoFocus: true,
source: validOptions
})
.keyup(function() {
var isValid = false;
for (i in validOptions) {
    if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
        isValid = true;
    }
    }
    if (!isValid) {
     this.value = previousValue
} else {
    previousValue = this.value;
}
});

So these letters: Bold", "Normal", "Default", "100", "200" work. BUT

As soon as i change the validOptions to:

var validOptions ='@Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=' + $("#Form_Prod_Num").val();

It doesn't work as it should.

is there another way to do this, or do you know where i'm going wrong.

This question is about an alternative to .keyup

SerialProdNumStockSiteAutoComplete code:

         public JsonResult SerialProdNumStockSiteAutoComplete(string term,string stocksitenum,string model)
    {
        return Json(AutoComplete.DeviceFromStockSite(term, stocksitenum, model), JsonRequestBehavior.AllowGet);
    }

Device from stock:

 public static List<string> DeviceFromStockSite(string term, string stocksitenum, string model)
    {
        //devices will always come from serialised stock
        var qryStock =
            SC42Ctx.SPNlocs
                .Where(x => x.Nloc_Site_Num.StartsWith(stocksitenum)
                            && x.Nloc_Part_Num == model
                            && x.Nloc_Ord_Num == null)
                .Select(
                    s =>
                        new TicketSerialNumber
                        {
                            SerialNumber = s.Nloc_ID_Num,
                            Source = stocksitenum,
                            Call = s.Nloc_Ord_Num.ToString()
                        })
                .ToList();

When i copy the URL this shows:

http://localhost:58172/Ajax/SerialProdNumStockSiteAutoComplete?stocksitenum=LW&model=MP4000BADP&term=4&_=1433235435372

This was when i entered 4 and couldnt add anything else

Gillman answered 2/6, 2015 at 8:25 Comment(13)
possible duplicate of Using .keyup function to filter auto completeKarli
As in your duplicate, #30571748, the version that works is an array, the version that doesn't is a string.Karli
its not same, am asking if theres another alternative for .keyup, the other question i have not got an answer, so i want to ask a new question to change everything, instead of telling me my error can you please try giving a solutionGillman
check what is coming from the server side. console.log(vaidoptions)Ilene
could you post your SerialProdNumStockSiteAutoComplete method code ?Vehemence
Just verify response body in browser's console ?Vehemence
added to question, look above pleaseGillman
@freedomn-m i have found the url in console, look above pleaseGillman
@mali Sorry - should have noticed this much sooner - try @Html.Action not @Url.ActionKarli
@freedomn-m nah thats given me more errors: An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code Additional information: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.Gillman
Ok - I reviewed the options for Autocomplete. Providing a URL to the 'source' option tells autocomplete to get the data from that URL. My question now is: why do you have the .keyup code at all? Autocomplete does this for you jsfiddle.net/nm9mv0faKarli
because i want to show error when the users enters something other than data from auto complete. with the js fiddle users can enter random words which i want to stop happening. @freedomn-mGillman
@freedomn-m if i get rid of the keyup is there another way to show an error if it doesnt match the auto completeGillman
M
0
Try using the minLength option of autocomplete to specify the minimum number of characters: 

$('#ac').autocomplete({
autoFocus: true,
source: validOptions,
minLength: 3
})
.keyup(function() {
var isValid = false;
for (i in validOptions) {
    if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
        isValid = true;
    }
    }
    if (!isValid) {
     this.value = previousValue
} else {
    previousValue = this.value;
}
});
Menadione answered 2/6, 2015 at 8:33 Comment(0)
V
0

This code is culprit:

 if (!isValid) {
     this.value = previousValue
} else {
    previousValue = this.value;
}

What does it says is like value doesn't match then it will not let you enter that value.

Update your code as:

$(document).ready(function () {
    var validOptions = ["Bold", "Normal", "Default", "100", "200"]
    previousValue = "";

    $('#ac').autocomplete({
        autoFocus: true,
        source: validOptions
    })
        .keyup(function () {
        var isValid = false;
        for (i in validOptions) {
            if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
                isValid = true;
            }
        }

    });
});
Vehemence answered 2/6, 2015 at 8:36 Comment(6)
i want it to not let me enter values. thats the whole point of this, you can only enter the data. also am saying its not working when i add the url.action, so is there another way i can go about thisGillman
@mali in that case you need to use minLength property, I'll update my answer accordingly.Vehemence
min length didnt work, i used that, the problem is its stopping after the first letter. but the hard code works, but my url action doesn't allow it to work for some reason, also there is 3 different data coming as you can see in the questionGillman
@mali could you post your SerialProdNumStockSiteAutoComplete code?Vehemence
added to question, look above pleaseGillman
I have added the url when on console, its tricky this because it works hard code but not the way i implemented it, not sure whyGillman
K
0

an alternative to .keyup

show error when the users enters something other than data from auto complete

It appears that you want to use the Response event http://api.jqueryui.com/autocomplete/#event-response.

Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data... This event is always triggered when a search completes, even if the menu will not be shown because there are no results ...

This won't work in the fiddle with hard-coded data as it only applies when using a URL for the search (which you want).

The .keyup doesn't work as it occurs before the search has completed:

When you use hard-coded data (as per fiddle), all is fine, but when you change so that source is a URL, the URL is called (search is performed) by autocomplete (can be confirmed by viewing network in the browser console) - this takes a short time asynchronously while the .keyup occurs (as good as) immediately. You can confirm this by adding a Thread.Sleep() in your action and various console.logs in the js.

Karli answered 2/6, 2015 at 9:42 Comment(0)
G
0

Right i have found an answer

Something simple:

var source = validOptions;
            var found = $('.ui-autocomplete li').text().search(source);
            console.debug('found:' + found);
            if (found < 0) {
                $(this).val('');
                alert("please select from auto complete");
            }
Gillman answered 2/6, 2015 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.