I’m using typeahead to pull names and then updating a hidden field with the id respective to the name. In my form the name can be left blank, filling it is not a requirement.
Is there a way to add custom error checking to the typeahead function? for instance, I start filling out the form and type/select a user, then I change my mind and want to leave it blank. by this point, the user id is already added to the hidden field, so even if i leave the name field blank, the form will be passed with the user id in it.
I guess I can always do error checking on submit, but am curious if there is a way to add to the native api.
my code is:
$('#name_field').typeahead({
minLength: 3,
source: function (query, process){
$.get('/url/getsource', {query: query}, function (data) {
names = [];
map = {};
$.each(data, function (i, name) {
map[name.uName] = name;
names.push(name.uName);
});
process(names);
});
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
updater: function (item) {
selectedID = map[item].id;
$('#id_field').val(selectedID);
return item;
}
});
I was hoping I can add something like
$('#name_field').typeahead({
myCustom: function (){
if($('#name_field').val() == ''){
$('#id_field').val('');
},
rest,
of the,
function
});
You could bind a function to the blur event of the user field. So as soon as the user makes any changes to another form element if it is left blank you clear the typeahead field.