1

I am trying to implement a functionality where a user can select a list of items from the dropdown suggestions and save new items using a dialog box if and only if there are no suggestions. I am currently implementing it as follows,

suggestOpened = false;//Initially set flag to false
....
open: function(evt, ui) {
  suggestOpen = true; //Set the flag to true when the list is opened
}
change: function(event, ui) {
  if(!suggestOpened) {
    //open dialog box
  }
  suggestOpened = false; //List will be closed here so reset flag
}

The problem with this is that if the user returns to the field in the same session and wants to save another item, the flag will be set to false so the dialog will not be opened. Can I somehow have access to the response from the ajax request and find out if the response contained suggestions from the source?

Thanks, Roland

Awemo
  • 875
  • 1
  • 12
  • 25

1 Answers1

1

You're pretty close-- the change event can actually handle this:

$("#auto").autocomplete({
    source: ['hi', 'bye', 'foo', 'bar'],
    change: function (event, ui) {
        var newItem = !ui.item;

        if (newItem) {
            /* open your dialog */
            $("#dialog").dialog("open");
        }
    }
});

Example: http://jsfiddle.net/8RmRY/

The only caveat here is that if the user types something that exists in the list but does not physically select an item, newItem will be true. If that's a problem, I can expand my answer.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks for the answer. That is exactly what I am trying to implement. The problem you mentioned is however exactly what I am trying to avoid. I tried fiddling with the code you created [link]http://jsfiddle.net/8RmRY/6/, `suggestOpened` is reset to `false` in the close event before the change event is triggered. Any ideas on possible improvements? – Awemo Mar 15 '12 at 14:03
  • @Awemo: Does the "autoselect" plugin help you at all? https://github.com/scottgonzalez/jquery-ui-extensions/blob/master/autocomplete/jquery.ui.autocomplete.autoSelect.js – Andrew Whitaker Mar 15 '12 at 15:07
  • You must have some serious jquery-jutsu skills. I found a solution to my problem by referring to another of your answers. [link]http://stackoverflow.com/questions/4718968/detecting-no-results-on-jquery-ui-autocomplete/4719848#4719848 . I check if the length of contents is less than 1, meaning there were no results, and proceed with the dialog box. – Awemo Mar 16 '12 at 11:46