I'm using typeahead.js to assign a product id to a hidden html form field. This works great when there's a match:
$('.products_tt .typeahead').typeahead
name: 'products_tt',
prefetch:
url: '/products.json',
ttl: 60 * 5e3
template: '<p><strong>{{value}}</strong> – {{year}}</p>',
engine: Hogan
$('.products_tt .typeahead').on "typeahead:selected typeahead:autopleted", (e,datum) ->
$('#disk_file_product_id').val(datum.id)
I clear the hidden field when the input field is left blank:
$('.products_tt .typeahead').blur ->
if $(this).val().length == 0
$('#disk_file_product_id').val("")
But I also need to clear the hidden field when text has been entered in the input field but there's NO match.
My Java/Coffeescript skills are weak so not sure how to do this?!?
I'm using typeahead.js to assign a product id to a hidden html form field. This works great when there's a match:
$('.products_tt .typeahead').typeahead
name: 'products_tt',
prefetch:
url: '/products.json',
ttl: 60 * 5e3
template: '<p><strong>{{value}}</strong> – {{year}}</p>',
engine: Hogan
$('.products_tt .typeahead').on "typeahead:selected typeahead:autopleted", (e,datum) ->
$('#disk_file_product_id').val(datum.id)
I clear the hidden field when the input field is left blank:
$('.products_tt .typeahead').blur ->
if $(this).val().length == 0
$('#disk_file_product_id').val("")
But I also need to clear the hidden field when text has been entered in the input field but there's NO match.
My Java/Coffeescript skills are weak so not sure how to do this?!?
Share Improve this question edited Aug 4, 2013 at 2:37 Meltemi asked Aug 3, 2013 at 18:44 MeltemiMeltemi 38.4k52 gold badges201 silver badges298 bronze badges2 Answers
Reset to default 5One of the following should work:
1) Hook into your input field's change
event first, and clear #disk_file_product_id
there. Your typeahead
events will later set this again if there was a selection. This also saves your the blur
callback.
$('.products_tt .typeahead').change ->
$('#disk_file_product_id').val("")
2) Clear #disk_file_product_id
in the opened
and closed
events, instead of in the field's change
event. I like this less.
$('.products_tt .typeahead').on "typeahead:opened typeahead:closed" ->
$('#disk_file_product_id').val("")
I know this is a few months old, but this is how you could do it:
Use jQuery to look at how many ".tt-suggestions" are in the DOM on each keyup event. If there are none, clear the hidden field.
$('.products_tt .typeahead').typeahead({
name: 'products_tt',
prefetch: url: '/products.json',
ttl: 60 * 5e3
template: '<p><strong>{{value}}</strong> – {{year}}</p>',
engine: Hogan
}).on("typeahead:selected typeahead:autopleted", function (e, datum) {
$('#disk_file_product_id').val(datum.id);
}).on('keyup', function () {
if($('.tt-suggestion').length === 0){
$('#disk_file_product_id').val("");
}
});