views:

28

answers:

1

Hello, I'm referencing the jQuery autocomplete plugin code seen in this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/how-to-use-the-jquery-ui-autocomplete-widget/

The problem with this tutorial is that it only support items found on the server. What I would like to do is allow a user to use items found on the server (as it works today) but also to allow user to input new values without the breaking the plugin... Example, so you could enter a user's email address, press enter, and then continue using the plugin, perhaps then finding another item on the server and again hitting return..

Ideas? Possible?

+2  A: 

You could try appending what is being typed in to the list of suggestions. That way they can essentially select what they are typing using "req.term". Like this:

//process response
$.each(data, function(i, val){                              
    suggestions.push(val.name);
});
//append what has been typed in so it's available for selection
suggestions.push(req.term);
//pass array to callback
add(suggestions);

Then, in the select: function, you could insert the selection into the database with an ajax call if it doesn't already exists.

//define select handler
select: function(e, ui) {

    //create formatted friend
    var friend = ui.item.value,
        span = $("<span>").text(friend),
        a = $("<a>").addClass("remove").attr({
            href: "javascript:",
            title: "Remove " + friend
        }).text("x").appendTo(span);

    //add friend to friend div
    span.insertBefore("#to");

    //insert selected email if doesn't already exists
},

Here's a keypress example for inserting you formated friend on enter:

$("#to").keypress(function(e){
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        e.preventDefault();

        //create formatted friend
        var friend = $(this).val(),
            span = $("<span>").text(friend),
            a = $("<a>").addClass("remove").attr({
                href: "javascript:",
                title: "Remove " + friend
            }).text("x").appendTo(span);

        //add friend to friend div
        span.insertBefore("#to");

        $(this).autocomplete('close');
    }
});
fehays
That's an interesting idea, thanks.. Concern with that is it differs from the facebook standard, which these days means the norm. Is there any way you see where when the user Presses return or enters a comma, the input is turned into a FRIEND?
AnApprentice
Yeah check my updated sample. I think it will work but you may need to play with it.
fehays