简体   繁体   中英

Remove text from textarea line by line

I did a code that removes the text on the textarea line by line. However it seems it is not working it removes the first line after that the third line and repeat again any one help me please this is the code i tried:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
$(document).ready(function(){
$('#remove').click(function(){
var textareavalue = $('#sometext').val().split("\n");

for(i=0; i < textareavalue.length;i++)
{
$('span').append('<br />Remove: '+textareavalue[i]);    
textareavalue.splice(0, 1);
$('#sometext').val(textareavalue.join("\n"));
}


});
});
</script>
</head> 







<textarea cols="40" rows="10" id="sometext"></textarea>
<br />
<button id="remove">Remove</button>
<br />
<span><span/>

You should use index 0 like this:

$('span').append('<br />Remove: '+textareavalue[0]); 

This is because the previous displayed element is removed with splice , so your next line is again at the first position.

Also change your loop condition, because your length is decreasing with this split :

while(textareavalue.length)

You should also give an id to our span , because other span tags may exist on your page (or in future).

It would be good to clear your span contents on every click, so it only shows the result of the last removal operation.

And it would probably be nice to not have it happen all at the same time, because then you just see the end-result. You could could use a timer like this:

HTML

<textarea cols="40" rows="10" id="sometext">
</textarea>
<br />
<button id="remove">Remove</button>
<br />
<span id="out"><span/>

JS

function removeLine() {
    if ($('#sometext').val().replace(/\n$/, '').length === 0) {
        // nothing to do
        return;
    }
    var textareavalue = $('#sometext').val().split("\n");
    // log line that will be removed
    $('#out').append('<br />Remove: '+textareavalue[0]); 
    // remove line
    textareavalue.splice(0, 1);
    $('#sometext').val(textareavalue.join("\n"));
    // remove next line with delay
    setTimeout(removeLine, 200);
}

$(function(){
    $('#remove').click(function(){
        // clear log
        $('#out').html('');
        setTimeout(removeLine, 200);
    });
});

Here is a fiddle .

for(var i=0, l = textareavalue.length; i < l; i++) {
    $('span').append('<br />Remove: '+textareavalue[0]);    
    textareavalue.splice(0, 1);
    $('#sometext').val(textareavalue.join("\n"));
}

Yes, because of using splice() method the array itself updating with new data and loop is also repeating on same array. Change the i value to 0 inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM