Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how do you loop through each newline of text typed inside a textarea?

Tags:

jquery

lets say inside a <textarea>, i type in a bunch of keywords on each new line.

keyword1
keyword2
keyword3
...




$('textarea[name=sometextarea]').val().split('\n').each(function(e){
alert($(this));                 
});
like image 711
aoghq Avatar asked Nov 13 '09 02:11

aoghq


2 Answers

The array object doesn't have any each method. As you are looping strings and not elements, use the jQuery.each method (instead of the jQuery().each method):

var lines = $('textarea[name=sometextarea]').val().split('\n');
$.each(lines, function(){
  alert(this);
});
like image 122
Guffa Avatar answered Sep 21 '22 13:09

Guffa


I think your problem is with the jquery object. val() returns a string and split() will return an Array. But each() is a property of the JQuery object. Try this instead:

$($('textarea[name=sometextarea]').val().split('\n')).each(function(e){
alert($(this));                                 
});

notice the extra $(...) around the the split() return.

like image 40
fserb Avatar answered Sep 22 '22 13:09

fserb