JamieAppleseed/selectToAutocomplete — Issue #32: Blur in 1.0.5 can erase input content
Author: chris20
Created: 2012-01-26 22:47:09+00:00
State: open

There's a bug in 1.0.5 that's not present in the 1.0.3 demo. It relates to the behavior when you tab out of the input field after having typed in a valid country name without having clicked in the list.

If I e.g. type 'brazil' and tab out of the box in 1.0.3, it works and will select Brazil. If I do this in 1.0.5 it will erase the content of the input field.

The cause is within the code that handles blur() starting at line 61 which contains the following statement:

if ( !($text_field.val() in valid_values) && ... [snip]

This will always fire because the test '$text_field.val() in valid_values' will typically return false (unless the input happens to be a number), since the "in" operator matches against the keys of the array, not the values.

My fix for this was a bit more involved than just allowing for this, as I also wanted to match case-insensitively and against the alternate spellings as well, so I ended up doing this:

$text_field.blur(function() {
var val = context.$text_field.val().toLowerCase().trim();
var matching_option = { 'real-value': false };
for (var i=0; i < context.options.length; i++) {
if (val === context.options[i]['label'].toLowerCase()) {
matching_option = context.options[i];
break;
}
};
if (matching_option['real-value'] === false) {
for (var i=0; i < context.options.length; i++) {
var matches = context.options[i].matches.split(' ');
for (var j = 0; j < matches.length; j++) {
if (val === matches[j].toLowerCase()) {
matching_option = context.options[i];
break;
}
}
};
}
if (context.$select_field.val() !== matching_option['real-value']) {
context.$select_field.val(matching_option['real-value'] || '');
context.$select_field.change();
}
if (matching_option['real-value']) {
context.$text_field.val(matching_option['label']);
}
if (typeof context.settings['handle_invalid_input'] === 'function' && context.$select_field.val() === '') {
context.settings['handle_invalid_input'](context);
}
});