I\'m using jquery, and I have a textarea. When I submit by my button I will alert each text separated by newline. How to split my text when there is a newline?
var ks = $('#keywords').val().split("\n");
inside the event handleralert(ks[k])
instead of alert(k)
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
e.preventDefault();
var ks = $('#keywords').val().split("\n");
alert(ks[0]);
$.each(ks, function(k){
alert(ks[k]);
});
});
});
})(jQuery);
Demo
Try initializing the ks
variable inside your submit function.
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
var ks = $('#keywords').val().split("\n");
e.preventDefault();
alert(ks[0]);
$.each(ks, function(k){
alert(k);
});
});
});
})(jQuery);
It should be
yadayada.val.split(/\n/)
you're passing in a literal string to the split command, not a regex.
Just
var ks = $('#keywords').val().split(/\r\n|\n|\r/);
will work perfectly.
Be sure \r\n
is placed at the leading of the RegExp string, cause it will be tried first.
you don't need to pass any regular expression there. this works just fine..
(function($) {
$(document).ready(function() {
$('#data').click(function(e) {
e.preventDefault();
$.each($("#keywords").val().split("\n"), function(e, element) {
alert(element);
});
});
});
})(jQuery);
The problem is that when you initialize ks
, the value
hasn't been set.
You need to fetch the value when user submits the form. So you need to initialize the ks
inside the callback function
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
//Here it will fetch the value of #keywords
var ks = $('#keywords').val().split("\n");
...
});
});
})(jQuery);