1

I've cobbled together a working autocomplete prototype, which adds the selected text as a span, this works fine. What I'd like to do is call this code from elsewhere though, so I have this:

$("#searchBox").autocomplete({
  var testSourceData = ["First thing", "Second thing", "Third thing"];

  source: testSourceData,

  select: function(e, ui) {
    //create formatted searchTerm
    addSearchTerm(e, ui);
    $(this).val('');
    return false;
  },
  ...
});

function addSearchTerm(e, ui) {
  var searchTerm = ui.item.value;
  var span = $("<span>").text(searchTerm);
  var a = $("<a>").addClass("remove").attr({
    href: "javascript:",
    title: "Remove " + searchTerm
  }).text("x").appendTo(span);

  //add searchTerm to searchBox
  span.insertBefore("#searchBox");

}

My question is this; the e and ui objects, where do they get passed from? If I want to call addSearchTerm from elsewhere, what do I need to pass it?

I'm currently trying to call it on the enter keypress, so I'm trying this:

$("#searchBox").keydown(function (event) {
  if (event.keyCode == 13) {
    addSearchTerm(event, $("#searchBox"));
  }
});

But I get the error:

Uncaught TypeError: Cannot read property 'value' of undefined`

So I'm obviously passing it the wrong data type. I thought $("#whatever") referenced an object, but I guess I'm wrong.

Any ideas or suggestions would be great, thanks.

1 Answer 1

1

Try this to trigger select event

$("#searchBox").keydown(function (event) {
  if (event.keyCode == 13) {
   $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item:{value:$(this).val()}});
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yup that did it, thank you! I guess I really need to read up on how JQuery refers to things, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.