Adding values to jQuery autocomplete real time
Asked Answered
W

3

7

I'm making a "token input" style checkbox with an autocomplete (user types in something, selects a response, which adds a "token" to the DOM view).

Using jQuery autocomplete, is there a way to add values that aren't in the source list after the user types them in?

For example, a source looks like ["Apples", "Oranges", "Bananas"]. The user types in "plums," when using the text field. Is there a way to add "Plums" to the list of sources if the user so desires? I know there are select and change events that I can check, but select only works if there's something to select (there isn't in this case), and change would require some kind of timeout check to verify that the user had stopped typing.

Conversely, is there another plugin I could use to accomplish this behavior?

Wicopy answered 11/6, 2012 at 17:14 Comment(2)
Couldn't you use the keyup event?Pseudo
change should work here. It includes a timeout after the person has stopped typing and has navigated away from the field. What problems did you encounter when trying to use it?Erythrocytometer
E
10

This should work fine with autocomplete's change event. This code assumes there's a button with id add that appears when you want to add a new item to the list. It will not appear if the user selects an item from the list. There are some tweaks that can be made, but this proof of concept should make it possible:

var source = ["Apples", "Oranges", "Bananas"];

$(function () {
    $("#auto").autocomplete({
        source: function (request, response) {
            response($.ui.autocomplete.filter(source, request.term));
        },
        change: function (event, ui) {
            $("#add").toggle(!ui.item);
        }
    });

    $("#add").on("click", function () {
        source.push($("#auto").val());
        $(this).hide();
    });
});

Here's an example: http://jsfiddle.net/rmGqB/


Update: Sounds like I slightly misunderstood the requirement. You can also tap into the result that autocomplete would populate the candidate list with and drive the visibility of the button based on whether or not the results of the search yielded any exact matches:

var source = ["Apples", "Oranges", "Bananas"];

$(function () {
    $("#auto").autocomplete({
        source: function (request, response) {
            var result = $.ui.autocomplete.filter(source, request.term);

            $("#add").toggle($.inArray(request.term, result) < 0);

            response(result);
        }
    });

    $("#add").on("click", function () {
        source.push($("#auto").val());
        $(this).hide();
    });
});

Example: http://jsfiddle.net/VLLuJ/

Erythrocytometer answered 11/6, 2012 at 17:37 Comment(6)
Doesn't using the change event require the field to be blurred? My concern is that if the user enters a new value, there will be no search results returned (behaves like a normal text field). How would they know to "add" the new value if there's nothing indicating that it's new? Is there a way to hook into what's returned by the search method?Wicopy
So you'd like to add an item to the list the minute the source array doesn't include it? Wouldn't that cause every single character the person typed to be placed in the source array? Or am I misunderstanding?Erythrocytometer
Sorry, I don't think I'm communicating the idea properly. The requirement is that the user types in a term, which triggers the autocomplete. If they don't see what they want in the available list of options, they can then add the term somehow (button, hitting enter, etc), which puts it in the list and also selects it. This is why I don't know if "change" would work. If I were using remote JSON as a source, I think I could put in a callback, but that isn't the case here. The source is rendered inline with the page in this case.Wicopy
The answer to this would be quite helpful, although it seems the 'second' turned into a couple of years now.Legroom
@mrq: What about the section marked Update and the edit date that occurred a few minutes after the comment?Erythrocytometer
if you want to get the button to hide again if the user actually selects from the array once the ADD button appears - see my alternative solution using the jquery UI method "change" within autocomplete.Amundson
A
1

The answer provided by Andrew causes the ADD NEW button to remain, even if the user then selects an existing item from the array instead of adding "new" !!!

Instead of included a toggle on the 'add' button, there's a built in .change function within autocomplete which can be used.

Although "Change" waits until the text box loses focus, this can be a better interface to then show the ADD BUTTON if there isn't a match to the array. (or could create a "confirm" of adding).

See alternative code which actually hides the "Add Button" again if the user selects from the array. Something which Andrew Whitaker's solution doesn't do :

$(function () {

  var source = ["Apples", "Oranges", "Bananas"];

  $("#auto").autocomplete({
    source: function (request, response) {
        var result = $.ui.autocomplete.filter(source, request.term);


        response(result);
    },
    change: function( event, ui ) {
      var $label = $(this);
      // figure out the id of hidden input box from label id
      var $id = $('#'+this.id.replace('label_','id_'));
      if ( ui.item === null && $label.val() != '' ){
        $("#add").show();            
      }
        if( ui.item != null && $label.val() != '' ){
        $("#add").hide();            
      }
    }
  });

  $("#add").on("click", function () {
    source.push($("#auto").val());
    $(this).hide();
  });

});

See my revised Fiddle in action - http://jsfiddle.net/VLLuJ/25/

Amundson answered 12/7, 2014 at 22:32 Comment(0)
N
0

Old question, but useful answer:

To update the autocomplete source, use the setter:

$("#auto").autocomplete("option", "source", ["Apples","Oranges","Bananas","Plums"]);

See http://api.jqueryui.com/autocomplete/#option-source

Nuptials answered 15/6, 2017 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.