typeahead.js
typeahead.js copied to clipboard
send different field from the displayed one
Hi, my json source is in the form
[{
"name": "Como",
"code": "CODE1"
}, {
"name": "Cagliari",
"code": "CODE2"
}]
and the typeahead init is (obiouvsly the source is Bloodhound)
$('#custom-templates .typeahead').typeahead(null,
{
name: 'code',
value: 'code',
highlight: true,
display:'name',
source: suggestions.ttAdapter(),
limit:3,
templates: {
suggestion: function (c) {
return Mustache.render('<div><b>{{name}}</b> {{country}}</div>', c);
}
}
});
The dropdown shows the name field and it's ok, but on form submit I have to send the "code" field, how can I do that?
I have the same problem!
still on with this problem. I'm sure there is a smarter way other than an hidded input field..
As far as I can tell the hidden input field is the smartest way to solve this:
$('#custom-templates .typeahead').on('typeahead:select', function(e, selected) {
console.log('selected', selected) // object with both 'name' and 'code'
// ...
})
All other options I can think of are way more hacky and prone to errors.
I think of Typeahead.js as an input field augment: HTML input fields do not support such feature (display name, return code).
I created a fiddle to play around: https://jsfiddle.net/xgLcesc5/
Maybe in some cases would be useful this data-attr solution https://jsfiddle.net/alfredopacino/xgLcesc5/4/ Obiouvsly you need extra work before submit the form (check each typeahead field of the form and send its data-code attribute)
Hi guys, i have same problem. Some one find way send keyvalue in hidden imput ?
there are 2 jsfiddle to accomplish that (hidden field or data-attribute). We have discussed here how to do that without extra code at all.
This would really be a nice built-in feature. I actually assumed it was already a thing.
Something like:
$('#mytypeaheadfield').typeahead(null, {
source: suggestions.ttAdapter(),
display: function(obj) { return obj. name; },
value: function(obj) { return obj.code; }
});
I think either the hidden field or the data-attr would work.
Try it.
$('#mytypeaheadfield').typeahead(null, {
source: suggestions.ttAdapter(),
display: code,
templates: {
suggestion: Handlebars.compile('<div>{{name}}</div>')
}
});
display is actually the "value" and templates.suggestion is the format of displayed typeahead options.
In order to use this solution, you have to add this piece of code in the page (html, hbs):⬇
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
once that uses handlebars to compile the options.