2013-07-21 24 views
0

好了當我點擊與類的按鈕「allas」我想,jQuery的追加按鈕的文本到我的id爲「輸入框」輸入刪除文本。到目前爲止,所有的作品好:如何追加和從輸入

$(document).ready(function() { 
    $('.allas').click(function() { 
     $('#inputbox').val($(this).text()); 
    }); 
}); 

但是第一個問題是我的代碼總是會替換輸入VAL,當我與類「allas」另一個按鈕點擊。我希望jquery增加了一個分隔的值;

以及「我覺得比較難的部分:」我想撤銷功能,當用戶再次點擊,他又按下了按鈕的值應該從輸入被delted的按鈕!

我希望你能明白嗎?感謝幫助!

http://jsfiddle.net/WcCTe/

+1

你能張貼你的'html' – Pumpkinpro

+0

http://jsfiddle.net/WcCTe/ –

回答

1

一個簡單的方法來做到這一點:

var inputValues = []; 
$(document).ready(function() { 
    $('.allas').click(function() { 
     var inputValue = $(this).text(); 
     var index = inputValues.indexOf(inputValue); 
     if (index >= 0){ 
      inputValues.splice(index,1); 
     } 
     else{ 
      inputValues.push(inputValue); 
     } 
     $('#inputbox').val(inputValues.join(";")); 
    }); 
}); 

DEMO

如果您不希望存儲全局變量,試試這個:

$(document).ready(function() { 
    $('.allas').click(function() { 
     var inputValues = []; 
     if ($('#inputbox').val() != "") 
     { 
      inputValues = $('#inputbox').val().split(";"); 
     } 
     var inputValue = $(this).text(); 
     var index = inputValues.indexOf(inputValue); 
     if (index >= 0){ 
      inputValues.splice(index,1); 
     } 
     else{ 
      inputValues.push(inputValue); 
     } 
     $('#inputbox').val(inputValues.join(";")); 
    }); 
}); 

DEMO

+0

很抱歉,但不會一部分工作:http://jsfiddle.net/WcCTe/1/ –

+1

檢查我的更新答案,http://jsfiddle.net/WcCTe/2/ @EmSta –

+1

您的代碼令人震驚的好!男人謝謝你!只有14行,你是上帝! –

1

儘量保持價值的歷史。

Fiddle Demo

HTML

<input type="text" id="inputbox" value=""><br> 
<button class="allas">one</button> 
<button class="allas">two</button> 
<button class="allas">three</button> 
<button class="undo">undo</button> 

文檔準備

$(function() 
{ 
    var history = ['']; 

    $('.allas').click(function() 
    { 
     var $this = $(this); 
     var $inputbox = $('#inputbox'); 
     var value = $inputbox.val() + $(this).text(); 
     history.push(value) 
     $inputbox.val(value); 
    }); 

    $('.undo').click(function() 
    { 
     history.pop(); 
     var lastIndex = history.length - 1; 
     var $inputbox = $('#inputbox'); 
     var value = history[lastIndex]; 
     $inputbox.val(value); 

    }); 
});