Question

I have this little text area in a page, that I wish to simply prepend ">>" to each line.

I thought it might be as simple as:

   $("#mytextarea").prepend("EvilHacker001>>");

But that didn't do anything. I've looked around and I couldn't find anything like foreach('line') relating to textarea.

Is there an easy way to do this?? Thanks.

Was it helpful?

Solution

For each line:

$('textarea').val(function(_, value){
   var arr = value.split('\n');
   for (var i = 0; i < arr.length; i++) 
        arr[i] = "EvilHacker001>>" + arr[i];
   return arr.join('\n');     
});

http://jsfiddle.net/DpQS4/

For each value:

$('textarea').val(function(_, value){
   return "EvilHacker001>>" + value;
});

Update:

$('textarea').keyup(function (e) {
    if (e.which == 13) {
        $(this).val(function (i, value) {
            return value + '>>';
        })
    }
});

http://jsfiddle.net/hBcHS/

Or:

$('textarea').keyup(function (e) {
    $(this).val(function (i, value) {
        return value.replace(/\n(?!>)/g, '\n>>');
    })
})

OTHER TIPS

prepend() adds the specified mark-up into the object returned by the jQuery selector (in this case the textarea). A textarea can contain only text, no other child elements; therefore you're trying to create invalid html.

If you want to prepend new text into the textarea:

$('#mytextarea').val(
    function(i,val){
        return 'EvilHacker001>> ' + val;
    });

You can try this one:

 $('#myTextarea').val(function(i, value){
   return value.split('\n').join('\nEvilHacker001>>');     
 });

You have to get the newline character \n and then split and join with \nEvilHacker001>>.

Get in the Fiddle here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top