1

こんにちは<input type="text" id="tempID" />、フォームに要素があります

私のフォームにも<input type="button" onclick="doSomething()" />要素があります。

ユーザーがボタンをクリックしたときに、テキスト ボックスの値をテキスト ボックスの履歴に追加したいと考えています。

Jquery ajaxを使用してリクエストを処理しています。だから私はjavascriptまたはJqueryでそれをしなければなりません。

<input type="text" />javascript/Jquery を使用して特定の要素の履歴に値を追加することは可能ですか?

4

2 に答える 2

2

HTML5LocalStorageを使用してこれを行う方法は次のとおりです

$( "#tempID" ).autocomplete({
  source: function( req, resp ) {

    var temp = localStorage.getItem('custom_history');  

    var data = JSON.parse(temp);
    resp( data );

}
});


$('#tempID').on('blur', function() {
    var temp = localStorage.getItem('custom_history');  

    var data = JSON.parse(temp); 
    if($.trim(this.value).length > 0)
       data.push(this.value);

    localStorage.setItem('custom_history', JSON.stringify(data)); 

});

私がやっていることは、ユーザーが入力フィールドから離れて別の場所をクリックしたときに、HTML5ローカルストレージに値を設定することです。

次に、それを取得し、jQueryUIオートコンプリートのソースとして設定します。

これが実用的なフィドルですhttp://jsfiddle.net/joycse06/EBduF/173/

値を入力してください。別の場所をクリックします。もう一度クリックして、他の値を追加します。フィドルを更新し、それらの1つを入力し始めると、オートコンプリートが表示されます。

アップデート

彼のコメントに基づいて、後で彼が必要とする最終的なコードはこれですチャットします、それが後で誰か他の人かもしれない場合、私は貼り付けています

// if we dont set this line then ff will return null, and null.length will throw an error
if(!localStorage.getItem('custom_history'))
        localStorage.setItem('custom_history','');
 $( "#test" ).autocomplete({
    source: function( req, resp ) {
      var term = req.term;
      var temp = localStorage.getItem('custom_history');  
        var data = [];
        if(temp.length > 0)
           data = JSON.parse(temp);
       var intRegex = /^\d+$/; 
       data = $.map(data,function(val){
                if(intRegex.test(val)){
                   if(val.indexOf(term) != -1) 
                        return val;
                   else
                        return null;
                }
                else
                    return null;
             });
      resp( data );

    }
});


$('#save').on('click', function() {
    var temp = localStorage.getItem('custom_history'); 

      var data = [];
      if(temp.length > 0)
        data = JSON.parse(temp); 
      var value = $.trim($('#test').val());
      if(value.length > 0){
         if($.inArray(value,data) != -1){
             //alert('Duplicate'); 
             return;
         }

      }
      data.push(value);
      localStorage.setItem('custom_history', JSON.stringify(data)); // set item to localStorage
});
于 2012-05-18T09:28:11.847 に答える
0

localStorage次のように使用できます。

var arr = [];
$('input#tempID').on('click', function() {
   arr.push(this.value);
   localStorage.setItem('history', JSON.stringify(arr)); // set item to localStorage
});

その値を取得するには、

var temp = localStorage.getItem('history');

if(retarr) { // checking that data it stored in localStorage or not, if not exists temp = null
  var allHistories = JSON.parse(temp); // now you have history
  console.log(allHistories);
}

オートコンプリートのようなものが必要だと思います

于 2012-05-18T08:28:28.840 に答える