2013-07-21 2 views
0

"allas"클래스의 버튼을 클릭하면 그 jquery가 "inputbox"라는 ID를 가진 입력에 버튼의 텍스트를 추가하기를 원합니다. 지금까지 모두 잘 작동합니다입력에서 텍스트 추가 및 삭제 방법

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

그러나 첫 번째 문제는 내가 클래스 "allas"또 다른 버튼을 클릭하면 내 코드는 항상 입력 발을 대체한다는 것이다. 나는 jquery가 값에 의해 분리 된 것을 추가하기를 원한다.

"더 어려운 부분이 있다고 생각합니다."사용자가 아직 버튼의 값을 눌러 버린 버튼을 다시 클릭하면 입력 값이 없어집니다.

저를 이해 하시길 바랍니다. 도와 주셔서 감사합니다!

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); 

    }); 
}); 
관련 문제