Stupid Kid Stupid Kid - 2 months ago 20
jQuery Question

Making list from textarea value by new lines

This may be very easy to solve but my brain is dead for some reason I can't find out the right road to success :(

I have some text area where by pressing enter for each word or more words in one line I get an list item.

$(document).on('click','#addList', function(){
var lines = $('#list').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var list = JSON.stringify(texts);
for(var e=0; e<list.length; e++){
var li = li+'<li class="c1_2v">'+list[e]+'</li>';
}
$('.content').append($('<ul>'+li+'</ul>'));
});


By doing this $.trim I am getting problem if I have more words in one line but it is useful if I have more empty new lines or spaces before first word.

Example:

<textarea>
this is

a

something
that
I want to add to new lists
</textarea>


By my code and first for loop I get something like:
['this','is','a','something','that','I','want','to','add','to','new','lists']


By second for loop I get into
li tags every letter or character from [ to ]
inside
li
tags

I don't understand regex I saw many websites but it is not getting into my head so even if you add it as more easier answer without explanation what is used for what I wouldn't know how it works..

And this is basically what I need to get in .content div:

<ul>
<li class="c1_2v">this is</li>
<li class="c1_2v">a</li>
<li class="c1_2v">something</li>
<li class="c1_2v">that</li>
<li class="c1_2v">I want to add to new lists</li>
</ul>


I will add snippet how it works till now:



$(document).on('click','#addList', function(){
var lines = $('#list').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
var list = JSON.stringify(texts);
for(var e=0; e<list.length; e++){
var li = li+'<li class="c1_2v">'+list[e]+'</li>';
}
$('.content').append($('<ul>'+li+'</ul>'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="list"></textarea>
<button id="addList">Add</button>
<div class="content"></div>





And also there is something undefined Idk what :(

As @AlexKudryashev commented I used array as string not as array and if I add var li before for loop undefined will go away.

Answer Source

Here is a simplified solution that requires no regex. You can use array.filter and array.map to consolidate.

document.querySelector('button').onclick = () => {
  var text = document.querySelector('textarea').value;
  var lines = text.split('\n');
  var html = lines
    .filter(line => line.trim() !== '')
    .map(line => `<li class="c1_2v">${line}</li>`)
    .join('');
  document.querySelector('ul').innerHTML = html;
}
<textarea>
    this    is 

a

something
that
I want to add to new lists
</textarea>

<button>Click me</button>

<ul><!--output goes here--></ul>