2016-08-01 4 views
-1

사용자가 "바구니에 추가"버튼을 클릭하면 텍스트 영역에 제품 제목을 추가하는 자바 스크립트가 있습니다.클릭 핸들러를 사용하여 textarea에서 문자열의 일부를 제거하십시오.

<a href="#" class="add-button" data-id="@fieldset.Id" data-producttitle="@fieldset.GetValue("productItemTitle")">Tilføj</a> 

그리고 자바 스크립트

var productTitle = settings.productTitle;   
$(".tilvalg textarea").text($(".tilvalg textarea").text() + productTitle + "\n"); 

가 어떻게 텍스트 영역에서 그 라인을 제거 할 경우 특정 라인에 대한 삭제 버튼을 사용자가 클릭?

텍스트 영역은 다음과 같이 수 : 사용자가 3 개 제품

사용자가 다음 제품 2의 "제거"를 클릭하면

을 추가 한 경우

Product name 1 
Product name 2 
Product name 3 

는, 텍스트 영역이

과 같아야합니다
Product name 1 
Product name 3 

나는 이것을 달성하는 방법을 잘 모르겠습니다.

+0

클릭 제품 2의 "제거"? 무슨 소리 야? 무엇이 제거됩니까? – nicael

답변

0

배열을 사용하여 문자열을 저장하고 (그리고 정렬 할 수 있도록) JavaScript를 변경 한 다음 출력하기 전에 목록을 수정할 수 있습니다. 뭔가과 같이 : 현재 행 정확히 경우

var items = []; 

// on click for adding 
    items.push(productTitle); // Add item to end of array 
    $(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output 

// on click for removing 
    var index = items.indexOf(productNameToFind); // Find an item in the array 
    if(index != -1) 
     items.splice(index, index); // Remove item at found index 
    $(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output 
0

당신이 볼 수있는 내용을 당신은 textarea 내부의 caret의 위치를 ​​얻을 필요가

$('#YourRemoveButton').on('click', function() { 

     var lines = $('#box').val().split(/\n/); 
     lines['YourLineIndex - 1 '] = ""; 
     lines = lines.filter(function(v){return v!==''}); 
     $("#box").val(lines.join("\n")); 

    }); 
0

그런 짓을하고 분할 할 수 있습니다 당신이 찾고있는 가치. 내가 예를 들어 텍스트 TEXT TO REMOVE 사용이 예에서

:

$('#btn1').click(function() { 
 
    // Get caret position 
 
    cur = $('#ta').prop("selectionStart"); 
 
    
 
    // Save the value of the textarea 
 
    str = $('#ta').val(); 
 
    
 
    beforeCursor = str.substr(0, cur); 
 
    afterCursor = str.substr(cur); 
 
    
 
    splitted_before = beforeCursor.split("\n") 
 
    splitted_after = afterCursor.split("\n") 
 
    lastline_before = splitted_before.pop(); 
 
    firstline_after = splitted_after.shift(); 
 
    
 
    fullline = lastline_before + firstline_after; 
 
    
 
    if (fullline == "TEXT TO REMOVE") { 
 
    new_str = splitted_before.join("\n") + "\n" + splitted_after.join("\n") 
 
    $('#ta').val(new_str) 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="ta" style="width: 450px; height: 250px;"></textarea><br /> 
 
<button id="btn1">Remove</button>

관련 문제