Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text in textarea line by line

I am using textarea to take user input. and want to read line by line. But it's not displaying anything I want to make a comma seperated list of the text in different lines

JS:

$('input[type=button]').click( function() {
    string = document.getElementById("hi").val();
    alert(string); 
    var html="";
    var lines = $('#id').val().split('\n');
    for(var i = 0;i < lines.length;i++){
        //code here using lines[i] which will give you each line
        html+=lines[i];
        html+=",";
    }
    $("#inthis").html(string);
});

HTML:

<textarea id="hi" name="Text1" cols="40" rows="5" placeholder="enter one wdg in one line" ></textarea>

<input type="button" value="test" />
<div id="inthis"></div>

Here is the jsfiddle:

http://jsfiddle.net/pUeue/1077/

like image 878
ALBI Avatar asked Dec 30 '25 01:12

ALBI


2 Answers

Here's updated js...

Demo Fiddle

$('input[type=button]').click(function () {
    var html = "";
    var lines = $('#hi').val().split('\n');
    for (var i = 0; i < lines.length; i++) {
        //code here using lines[i] which will give you each line
        html += lines[i];
        html += ",";
    }
    html = html.substring(0,html.length-1);
    $("#inthis").html(html);
});
like image 53
nik Avatar answered Jan 01 '26 17:01

nik


Firstly you have a confused mix of native javascript and jQuery code in your example. A native DOM element has no val() method for example, that's jQuery. Secondly, you could massively simplify your code by just using split() and join(','). Try this:

$('input[type=button]').click( function() {
    var string = $("#hi").val().split('\n').join(',');
    $("#inthis").html(string);
});

Example fiddle

like image 43
Rory McCrossan Avatar answered Jan 01 '26 16:01

Rory McCrossan