leompeters
leompeters

Reputation: 1035

Use html input data field attribute on bootstrap typeahead

I'm trying to get a data-field attribute to select what field of my "objects.json" will be used as source of my Bootstrap Typeahead input text, like:

form.html

<input type="text" data-provide="typeahead" data-field="name">

form.js

$("[data-provide=typeahead]").typeahead({
  source: function(query, process) {
    return $.get("/objects.json", {
      query: query
    }, function(data) {
      return process($.map(data, function(o) {
        return o[$(this).data('field')];
      }));
    });
  }
});

objects.json

[{"id":1,"name":"lorem"},
 {"id":2,"name":"ipsum"},
 {"id":3,"name":"dolor"}]

The problem is the "$(this).data('field')" on Javascript isn't get the HTML data-field attribute.

Thanks in advance!

Upvotes: 1

Views: 4411

Answers (3)

Bruno Monteiro
Bruno Monteiro

Reputation: 4519

Not sure if this applies to you, but in my case, I figured that data-field does not work. I tried to search online to see if "field" is a reserved word but couldn't find anything. Anyway, changing the data attribute to anything else (e.g: data-myfield, data-fieldID, etc.) worked for me.

Upvotes: 1

Leo
Leo

Reputation: 1231

Try this:

$("[data-provide=typeahead]").typeahead({
   source: function(query, process) {
     return $.get("/objects.json", {
     query: query
   }, function(data) {
      return process($.map(data, function(o) {
        return o[$(this).attr('data-field')]; //<-- Use attr()
      }));
     });
   }
});

Upvotes: 0

Tobias Hagenbeek
Tobias Hagenbeek

Reputation: 1213

have you tried to use $(this).attr('data-field')? i also you may want to look here: http://api.jquery.com/attribute-equals-selector/ that may also be some of your problem, depending on wether you even get your initial element

Upvotes: 0

Related Questions