Convert textarea content to html - javascript

I need to make a simple Javascript converter, which would turn <textarea> input into html-formatted list.
This is how a sample input would look:
Brand: Brand1
Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /
Brand: Brand2
Model1 /Model2 /Model3 /Model4 /Model5 /Model6 /
And this would be the html after conversion:
<h3>Brand1</h3>
<ul>
<li>Model1</li>
<li>Model2</li>
<li>Model3</li>
<li>Model4</li>
<li>Model5</li>
<li>Model6</li>
</ul>
<h3>Brand2</h3>
<ul>
<li>Model1</li>
<li>Model2</li>
<li>Model3</li>
<li>Model4</li>
<li>Model5</li>
<li>Model6</li>
</ul>
Could any one provide some sample code to do that?
Thanks a lot

jQuery would be the easy way to do this, but if you're forced to do it with pure Javascript, you'll have something that looks like this:
HTML:
<textarea id="input" rows="5" cols="60">Brand: Brand1
Model1 /Model2 /Model3 /Model4 /Model5 /Model6
Brand: Brand2
Model1 /Model2 /Model3 /Model4 /Model5 /Model6
</textarea>
<input id="convertButton" type="button" value="convert" />
<div id="output"></div>
Javascript:
var convertButton = document.getElementById('convertButton');
convertButton.onclick = function(){
var input = document.getElementById('input');
var output = document.getElementById('output');
var lines = input.value.split( '\n' );
var html = '';
for( var i=0; i<lines.length; i++ ) {
if( lines[i].indexOf('Brand')===0 ) {
var brand = lines[i].split(':')[1];
html += '<h3>' + brand + '</h3>';
}
if( lines[i].indexOf('/')!==-1 ) {
var models = lines[i].split('/');
html += '<ul><li>' + models.join('</li><li>') + '</li></ul>';
}
}
output.innerHTML = html;
};​
Note that this solution doesn't do a lot of error checking, and it would get pretty confused if you weren't careful with your input, but it should give you a starting place to do what you want. See a live demo here: http://jsfiddle.net/GUQXf/4/

Related

How to parse XML in JavaScript

https://jsfiddle.net/recklesswish/6yw1tdwh/5/ The following link has the JSON and i have converted this particular JSON in XML. Now the issue is I am not getting that how to parse it using javascript.
Here is the code of xml, JSON resp.
XML
var carsData = "<cars>
"<Honda>"
"<model>Figo</model>"
"</Honda>"
"<Honda>"
"<model>City</model>"
"</Honda>"
"<Audi>"
"<model>A6</model>"
"</Audi>"
"<Audi>"
"<model>A8</model>"
"</Audi>"
"</cars>"
JSON
var carsData = '{"cars":{"Honda":[{"model":"Figo"},{"model":"City"}],"Audi":[{"model":"A6"},{"model":"A8"}]}}';
$('#newCollection').on('click', function() {
$(this).empty();
var data = JSON.parse(carsData);
$(this).append('New Collection<ul></ul>');
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
$(this).find('ul').append('<li>' + make + ' - ' + model + '</li>')
}
}
});
With HTML
<ul>
<li id="newCollection">New Collection</li>
</ul>
First of all make your xml look like this in javascript -
var carsData = "<cars><Honda><model>Figo</model></Honda><Honda><model>City</model>
</Honda><Audi><model>A6</model></Audi><Audi><model>A8</model></Audi></cars>"
And your JS code would look like this -
$('#newCollection').on('click', function() {
$(carsData).find("Honda").each(function() {
var model = $(this).find("model").text();
console.log("model: " + model );
});
});
newCollection is the id of your button. This will print model as below-
model: Figo
model: City
I would suggest you to go through basics first rather than trying to jump into coding directly. Clear basics will make you a good coder in long run :)
I see. Use below code to achieve what you want -
<body>
<h1>Hello</h1>
<button type="button" id="newCollection">Click Me!</button>
<ul id="myul"></ul>
</body>
And your JS code should be -
$('#newCollection').on('click', function() {
var data = $($.parseXML(carsData));
data.find('cars').children().each(function() {
var make = $(this).find("model").text();
$('#myul').append('<li>'+make+'</li>');
});
});

How to split multiple string using jQuery or javascript?

I know this been posted here: how to split the string using jquery or javascript
but in my case have multiple strings. It's working in a single line of string but if it's in a multiple lines it repeats the day after year. and for some reason it display's only the first 'li' value. Is it possible to display it this way:
<ul>
<li>
<div class="date">
<p class='day'>23</p>
<p class='month'>05</p>
<p class='year'>2013</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>25</p>
<p class='month'>07</p>
<p class='year'>2014</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>01</p>
<p class='month'>05</p>
<p class='year'>2014</p>
</div>
</li>
</ul>
here is my code:
html
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>
css:
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
script:
var data =$('.date').text();
var arr = data.split('-');
$(".date").html("<p class='day'>"+arr[0]+"</p>"+"<p class='month'>"+arr[1]+"</p>"+"<p cass='year'>"+arr[2]+"</p>");
jsfiddle:
demo
thanks Bon
You are getting the text from the first element, and changes all elements to contain the code for that. You need to loop through the elements and convert the content in each one.
You can use a callback function in the html method to do that, it will get the original HTML code from each element, and you return the new HTML code for that element:
$(".date").html(function(i, h) {
var arr = h.split('-');
return "<p class='day'>"+arr[0]+"</p><p class='month'>"+arr[1]+"</p><p class='year'>"+arr[2]+"</p>";
});
Demo: http://jsfiddle.net/Guffa/815c95jn/1/
(Note the difference in function, as this will get the HTML code in each element instead of the text. As long as there is no actual HTML markup in the elements, like in your example, there is no difference in the result.)
An alternative to splitting the text is to use replace:
$(".date").html(function(i, h) {
return "<p class='day'>" + h.replace("-", "</p><p class='month'>").replace("-", "</p><p class='year'>") + "</p>";
});
You only selected one .date, but you have to iterate over all of them, e.g. using $.each():
$(".date").each(function () {
var data = $(this).text();
var arr = data.split('-');
$(this).html("<p class='day'>" + arr[0] + "</p>" +
"<p class='month'>" + arr[1] + "</p>" + "<p class='year'>" + arr[2] + "</p>");
});
Adjusted Fiddle, and for reference: http://api.jquery.com/each/
Since the title asks about how to completed this with jQuery or Javascript (assuming vanilla JS) let me give a quick example of how this might be done without the need for jQuery:
var dates = document.querySelectorAll('.date');
var dateClasses = ['day', 'month', 'year'];
Array.prototype.forEach.call(dates, function(date){
var dateString = date.innerHTML;
var dateStringArray = dateString.split('-');
var content = "";
for(var i = 0; i < dateStringArray.length; i++){
var newDate = document.createElement('p');
newDate.classList.add(dateClasses[i]);
newDate.innerHTML = dateStringArray[i];
content += newDate.outerHTML;
}
date.innerHTML = content;
});
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>

Output html tag as text into a div, each array element on separate line

I have an array in javascript file called newElements.
The format likes this:
newElements: Array[3]
0: "<p class='Day'>asdasd</p>"
1: "<p class='Day'>123123</p>"
2: "<p class='Day'>Test</p>"
length: 3
And I have a div.panel-body.
What I did is
for( var i = 0; i < newElements.length; i++) {
new_content += newElements[i];
}
$(".panel-body").text(new_content);
It gives me output looks like this:
However, I want the div format like this:
<p class="Day">Some Text</p>
<p class="Day">Another Text</p>
<p class="Session">TEXT</p>
Each html tag on a separate line.
Yes, I know the <br> tag, but the question is, if I add <br> , the <br> tag will be treated as plain text, the output will become like this: <p class="Day">asdasd</p><br><p class="Day">asds</p>
So, could someone give me a nice way to show the output to screen the way I want it. You already have the array I give you.
And if I use html() function, the <p> will be treated as real html tag, that's not what I want, I want they be shown.
If you don't want to display the code, instead of .text(), use .html().
Fiddle: http://jsfiddle.net/q4AeR/
My mistake. Since you DO want to show the actual code, add each to its own new element, within the loop. This is the best I can think of:
Fiddle: http://jsfiddle.net/Hb9mC/
Try
for( var i = 0; i < newElements.length; i++) {
$(".panel-body").append(document.createTextNode(newElements[i])).append('<br/>');
}
http://jsfiddle.net/9z3zE/1/
I assume you want to display your code including line breaks. Convert your HTML to entities and add line breaks:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
var newElements = ['<p class="Day">asdasd</p>,<p class="Day">123123</p>,<p class="Day">Test</p>'],
output = '';
for(var i = 0; i < newElements.length; i++) {
output += htmlEntities(newElements[i]) + '<br />';
}
$('.panel-body').html(output);
http://jsbin.com/mefuhufo/1/edit
<div class="hello">
</div>
<script>
var mycars = new Array();
mycars[0] = "<p class='Day'>Hello Xinrui Ma</p>";
mycars[1] = "<p class='Day'>this is the array</p>";
mycars[2] = "<p class='Day'>hopes it fits your need</p>";
var divHello = $('div.hello')
$.each(mycars, function( index, value ) {
divHello.append(value);
});
</script>

How do I remove the string values?

I was trying to figure out on how can I remove the string values. And also when I can remove them all? So here's the code.
HTML:
<div id="a"> </div>
<div id="x" onclick="EraseAll()"> </div>
JAVASCRIPT:
function ABC(){
document.getElementById('a').innerHTML += "<img src=\"buttonx.png\" id=\"Erase\" onclick=\"Erase()\"> </div>" + document.getElementById('n').value + document.getElementById('q').value + parseInt(document.getElementById('t').value);
}
Ive tried this code, but it won't work,
function Erase(){
var n = document.getElementById('n').value;
var q = document.getElementById('q').value;
var t = document.getElementById('t').value;
n = n.replace(n, " ");}
I'm still learning Javascript , so if any help would do, and also please only use Javascript, I've been asked to use Javascript only.
If I understand what you're looking for this should do it -
document.getElementById('n').value = '';
document.getElementById('q').value = '';
document.getElementById('t').value = '';

javascript write a line of html code with a button

hey guys i have got this far with a chat system but now i am stuck at this point.
the js script will look for a element called chat and if it is not found it will put it in with all of the other elements stated here
<div class='chat' id='chat'><div class='ch' id='ch'><h2>Chat</h2></div><div class='chatbox'><div class='messages'></div><textarea id='message' class='chatinp' rows='3' cols='27'></textarea><button class='send'>Send</button></div></div>
My problem is how to insert that whole line of code with javascript into the html document.
how would you do this?
My javascript script is you need to see
<script type="text/javascript">
var num = new Number();
num = 0
function chat(){
if(!document.getElementById("chat")){
document.write("<div class='chat' id='chat'><div class='ch' id='ch'><h2>Chat</h2></div><div class='chatbox'><div class='messages'></div><textarea id='message' class='chatinp' rows='3' cols='27'></textarea><button class='send'>Send</button></div></div>")
}
else
{
var obj = document.getElementById("chat").cloneNode(true);
var p = $(".chat");
var offset = p.offset();
num = num + 1;
if (num <15) {
obj.id = obj.id + num;
document.getElementById("ch").id = obj.id;
document.body.appendChild(obj);
document.getElementById("chat").style.left = "700px";
}
}
}
</script>
Don't use document.write (it will overwrite everything in your document), but create div#chat dynamically, something like:
if(!document.getElementById("chat")){
var chatdiv = document.createElement('div');
chatdiv.id = 'chat';
chatdiv.className = 'chat';
chatdiv.innerHTML =
['<div class="ch" id="ch">',
'<h2>Chat</h2></div>',
'<div class="chatbox">',
'<div class="messages"></div>',
'<textarea id="message" class="chatinp" ',
'rows="3" cols="27"></textarea>',
'<button class="send">Send</button></div>'
].join(' ')
document.body.appendChild(chatdiv);
}
[Edit 2022] A more modern approach may be:
document.querySelector(`#chat`) || (_ =>
document.body.insertAdjacentHTML(
`beforeend`, `
<div id="chat">
<div class="ch" id="ch">
<h2>Chat</h2>
</div>
<div class="chatbox">
<div class="messages"></div>
<textarea id="message" class="chatinp" rows="3" cols="27"></textarea>
<br><button class="send">Send</button>
</div>
</div>`)
)();
document.querySelector(`#chat #message`).placeholder = `Type something!`;

Categories