Reputation: 2736
I'm using Typeahead.js for my suggestions, with id / value combo. On select, I'm setting the value of a hidden element to id.
The problem is, when the user first selects something from Typeahead's suggestions, and than fills some other value manually - the old id value from Typeahead remains in the hidden element.
Is there a way to remove the hidden id input value, if the user didn't select it from Typeahead suggestions?
EDIT: The function that adds the id value:
$('.lang').on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(this).parent().parent().nextAll('.lang_id').val(datum.id);
});
The input:
<input type="hidden" class="lang_id" value="" name="lang_row[<?php echo $i; ?>][lang_id]" id="lang_row_[<?php echo $i; ?>]_lang_id"/>
Upvotes: 1
Views: 576
Reputation: 188
You can use combination of typeahead:selected and change event to track the changes and update the id of hidden input
$('.lang').on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(this).parent().parent().nextAll('.lang_id').val(datum.id);
// add selected text as data
$(this).parent().parent().nextAll('.lang_id').data('name',datum.name);
}).on("change", function(e,datum) {
var selectedval=$(this).parent().parent().nextAll('.lang_id').data('name');
if(selectedval!=$(this).val()){
console.log('ID reset to blank');
$(this).parent().parent().nextAll('.lang_id').val('');
}
});
Upvotes: 0
Reputation: 76
You should listen for a change event on the typeahead input, and when that occurs, remove the id from the hidden input because you know the user has entered text manually.
Upvotes: 1