From b7f6602f63bf85382ed287b6303fb04836c3ae97 Mon Sep 17 00:00:00 2001 From: Don Wilson Date: Sun, 11 Dec 2011 22:05:40 -0700 Subject: [PATCH] Revert to previously selected value when the field is left with invalid input --- jquery.select-to-autocomplete.js | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/jquery.select-to-autocomplete.js b/jquery.select-to-autocomplete.js index 2c89b62..fc44463 100644 --- a/jquery.select-to-autocomplete.js +++ b/jquery.select-to-autocomplete.js @@ -38,16 +38,16 @@ THE SOFTWARE. 'relevancy-sorting-strict-match-value': 5, 'relevancy-sorting-booster-attr': 'data-relevancy-booster', handle_invalid_input: function( context ) { - context.$text_field.val( '' ); + context.$text_field.val( context.$select_field.find('option:selected:first').text() ); }, handle_select_field: function( $select_field ) { return $select_field.hide(); }, - insert_text_field: function( $select_field ) { + insert_text_field: function( context ) { var $text_field = $( "" ); if ( settings['copy-attributes-to-text-field'] ) { var attrs = {}; - var raw_attrs = $select_field[0].attributes; + var raw_attrs = context.$select_field[0].attributes; for (var i=0; i < raw_attrs.length; i++) { var key = raw_attrs[i].nodeName; var value = raw_attrs[i].nodeValue; @@ -57,8 +57,14 @@ THE SOFTWARE. }; $text_field.attr( attrs ); } - return $text_field.val( $select_field.find('option:selected:first').text() ) - .insertAfter( $select_field ); + $text_field.blur(function() { + var valid_values = context.$select_field.find('option').map(function(i, option) { return $(option).text(); }); + if ( !($text_field.val() in valid_values) && typeof settings['handle_invalid_input'] === 'function' ) { + settings['handle_invalid_input'](context); + } + }); + return $text_field.val( context.$select_field.find('option:selected:first').text() ) + .insertAfter( context.$select_field ); }, extract_options: function( $select_field ) { var options = []; @@ -130,17 +136,17 @@ THE SOFTWARE. return this.each(function(){ var $select_field = $(this); - - var options = settings['extract_options']( $select_field ); - var $text_field = settings['insert_text_field']( $select_field ); - settings['handle_select_field']( $select_field ); - + var context = { '$select_field': $select_field, - '$text_field': $text_field, - 'options': options, + 'options': settings['extract_options']( $select_field ), 'settings': settings }; + + context['$text_field'] = settings['insert_text_field']( context ); + + settings['handle_select_field']( $select_field ); + if ( typeof settings['autocomplete-plugin'] === 'string' ) { adapters[settings['autocomplete-plugin']]( context ); } else {