ダブルクリックで、プルダウン<=>テキスト入力

chrome ブラウザ限定ですが、ダブルクリックでプルダウンとテキスト入力させるフィールドを jQuery で書いてみました。

f:id:posturan:20160313173232j:plain

このようなプルダウンで選択した状態で、、

f:id:posturan:20160313173302j:plain

ここで、ダブルクリックすると、、、

f:id:posturan:20160313173311j:plain

テキスト入力状態にさせます。→コピーペーストができる状態にします。
  ・テキスト入力(変更)Enterを押したらその文字列をプルダウンの選択リストに加え、value値として選択状態にさせてプルダウンに戻します。
  ・フォーカスを外した時も、同様にテキスト入力結果を反映させます。
  ・テキスト入力結果が選択リストにあるもと一致すれば、プルダウンリストへの追加は行われず、選択リストで一致するものが選択状態になってプルダウンにもどります。

この仕様で、汎用的に使用できる jQuery メソッドを書いてみました。

まず、テキスト入力結果とプルダウン選択リストを比較して選択リストを設定してテキスト入力フィールドを削除する関数を用意します。
これは、プルダウンの前にテキスト入力フィールドを配置するというルールで用意します。

var inputBackSelect = function(itag){
   var edited = $(itag).val().trim();
   var find = 0;
   $(itag).next().children().each(function(i, e){
      if ($(e).text()===edited){
         $(e).prop('selected', 'selected');
         find = 1;
      }else{
         $(e).removeAttr('selected');
      }
   });
   if (find==0){
      $(itag).next().children(':first').before('<option value="' + edited + '" >' + edited + '</option>');
      $(itag).next().val(edited);
   }
   $(itag).next().attr('style', $(itag).next().attr('style').replace(/display: none; /, ''));
   $(itag).remove();
};


次に、プルダウン、selectタグの id="address" に対して、ダブルクリックした時の
処理を書きます。

$('#address').dblclick(function(){
   $(this).before('<input type="text" value="' + $(this).children('option:selected').text() + '" style="width:' + $(this).width() + 'px">');
   $(this).prev().dblclick(function(){
      inputBackSelect($(this));
   }).keyup(function(eo){
      if (eo.keyCode==13){
         inputBackSelect($(this));
      }
   }).blur(function(){
      inputBackSelect($(this));
   });
   $(this).prev().select();
   $(this).css('display', 'none');
});

ダブルクリック→ before 挿入、挿入したテキストフィールドに対して
ダブルクリックなら、先に用意した関数を実行、
Enterキーの keyup で、先に用意した関数を実行、
フォーカスはずれたら、先に用意した関数を実行という設定行い、
テキストフィールドを全選択させて、
プルダウンを、cssの display: none で隠すということを実行しています。

これだけです。