jquery: prepopulating autocomplete fields

Posted by David Tildon on Stack Overflow See other posts from Stack Overflow or by David Tildon
Published on 2010-03-26T03:58:19Z Indexed on 2010/03/26 4:03 UTC
Read the original article Hit count: 424

Filed under:
|
|

I'm using the tokenizing autocomplete plugin for jquery ( http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry ). I mostly use Ruby, and I'm really unfamiliar with javascript, though.

My basic setup looks like this, and works fine for a new, blank form:

$(document).ready(function () {
  $("#tag_ids_field").tokenInput("/tags", {
    queryParam: "search"
  });
});

The problem comes when I try to prepopulate it, like for an edit page. I'm trying to do something like this (where the "#tag_ids_field" text box contains the JSON when the page is loaded - that way is just cleaner on the application side of things).

$(document).ready(function () {
  var tags = $("#tag_ids_field").html();
  $("#tag_ids_field").tokenInput("/tags", {
    queryParam: "search",
    prePopulate: tags
  });
});

However, when the page loads I see that it's just filled with hundreds of entries that read 'undefined'. I get this even if I take the JSON output that Rails provides and try sticking it right in the .js file:

$(document).ready(function () {
  $("#tag_ids_field").tokenInput("/tags", {
    queryParam: "search",
    prePopulate: "[{\"id\":\"44\",\"name\":\"omnis sit impedit et numquam voluptas enim\"},{\"id\":\"515\",\"name\":\"deserunt odit id doloremque reiciendis aliquid qui vel\"},{\"id\":\"943\",\"name\":\"exercitationem numquam possimus quasi iste nisi illum\"}]"
  });
});

That's obviously not a solution, I just tried it out of frustration and I get the same behavior.

My two questions:

One, why are my text boxes being filled with "undefined" tags when I try to prepopulate, and how can I get them to prepopulate successfully?

Two, I'm planning on having many autocomplete fields like this on the same page (for when several records are edited at once - they all query the same place). How can I make each autocomplete field take it's prepopulated values from it's own textbox? Something like (applying these settings to all input boxes with a certain class, not just the one of a particular id):

$(document).ready(function () { $(".tag_ids_field").tokenInput("/tags", { queryParam: "search", prePopulate: (the contents of that particular ".tag_ids_field" input box) }); });

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery