HTML: New Line not working - javascript

I basically just want to display each entry of local storage on a new line inside a list element.
Here is my JS:
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+'\n Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};
Very long i know, but this is the output I receive:
What is the reasoning for this? Do I not use line breaks right? or could it potentially be my CSS?

Unless you are using <pre> elements, or the equivalent CSS formatting, browsers treat newline characters as spaces, and condense multiple whitespace characters down to a single space. To have your fields appear on separate lines you need to insert <br> line break elements rather than newline characters. (Or use a nested list, or wrap each "line" in a <p> element, or whatever. But just using <br> elements is simplest.)
Except that because you are setting the text with .createTextNode() simply including "<br>" in your string would display those characters rather than creating an element. The simplest solution to this is to set the .innerHTML of your <li> element rather than using .createTextNode():
if (counter == 1) {
var json = JSON.parse(localStorage.getItem(localStorage.key(i)))
var textm = 'Entry:' + json.Entry + '<br> Exercise: ' + json.Exercise + '<br> Date:' + json.Date
+ '<br> Start: ' + json.Start + '<br> End: ' + json.End + '<br> Calories: ' + json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.innerHTML = textm;
ul.appendChild(li);
}
As an aside, you don't need a semicolon after the closing } of an if block. Also, assuming the above code is contained in a loop, it would be more efficient to move the line with var ul = document.getElementById("list"); to before the loop, so that you only have to lookup that element once instead of doing it on every loop iteration.

In html as W3Schools says,for breaking line we must use <br> instead of \n(or any other character).
I hope this helps :)

Here is your soultion
You need to create element. you can't pass it as a string
Example : document.createElement("br");
if ( counter == 1 ){
var json = JSON.parse(localStorage.getItem( localStorage.key( i )))
var textm = 'Entry:'+json.Entry+document.createElement("br")+' Exercise: '+json.Exercise+'\n Date:'+json.Date+'\n Start: ' +json.Start+'\n End: '+json.End+'\n Calories: '+json.Calories;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(textm));
ul.appendChild(li);
};

Update your text concatenation with <br/> instead of \n like below.
var textm = 'Entry:'+json.Entry+'<br/> Exercise: '+json.Exercise+'<br/> Date:'+json.Date+'<br/> Start: ' +json.Start+'<br/> End: '+json.End+'<br/> Calories: '+json.Calories;
li.innerHTML = textm;

Related

Getting HTML markup in a string compiled

I'm trying to give a HTML element a markup but it outputs in a string.
My code:
var inputString = tweet.text;
var findme = screen_name;
tweet.text = inputString.replace(screen_name, "<span class='searched'>" + screen_name + "</span>")
You're likely experiencing this issue because you're setting the string on the UI as text, not HTML. Elements have an innerHTML property which will create child elements if necessary.
DEMO
var inputString = "Hello Daniel!";
var findme = "Daniel";
var replacedString = inputString.replace(findme, "<span class='searched'>" +
findme + "</span>");
document.querySelector('#output').innerHTML = replacedString;
Try
.innerHTML
.replace outputs strings, not html
EDIT
var inputString = tweet.text;
var findme = screen_name;
tweet.text = inputString.replace(screen_name, "<span class='searched'>" + screen_name + "</span>")
SomeHTMLObject.innerHTML=tweet.text;
Found out the solution myself:
In the HTML page, you can should use HTML-escape. So you have to use {{{ variable }}} instead of {{ variable }}
Simple solution, should have thought about that..

Jquery out put values issue

I'm having some issues with jquery.
I have a variable amount of libox's that have specific values in them.
I want to grab the data and on clikc out put it to a text area. but I'm having some problems with it.
here is my code:
$(".bottomtri.single_add_to_cart_button").click(function() {
var slival = $("#mixers li .infora h3").text(),
slivalmix = $("#mixers li .mix-value").text(),
slivalimg = $("#mixers li .color-img").html(),
slivaltotal = slivalimg + slival + slivalmix;
$(".addon.addon-custom-textarea").val(slivaltotal);
});
with this snippet might out put is just mashing everything together and its also adding up the numbers.
What I want it to do is go through each one and out put it like a list.
so it would have an out put like
h3 mix-value color-img
h3 mix-value color-img
h3 mix-value color-img
h3 mix-value color-img
You need to loop over the slide elements, and build up an array of strings. Then after the loop you can join the items in the array, and separate them with line breaks. You also need to add seperaters when you concatenate the values.
$(".bottomtri.single_add_to_cart_button").click(function() {
var sliStrings = [];
$("#mixers li").each(function () {
var slival = $(".infora h3", this).text(),
slivalmix = $(".mix-value", this).text(),
slivalimg = $(".color-img", this).html(),
sliStrings.push(slivalimg + " " + slival + " " + slivalmix);
});
$(".addon.addon-custom-textarea").val(sliStrings.join('\n'));
});
You want spaces between the values, and you want numbers to be treated like text, then you have to put spaces in the output, this will also avoid numbers being added together
slivaltotal = slivalimg + " " + slival + " " + slivalmix

js/jquery iterate through html elements to dynamically build a string

I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"

Javascript - Regex : How to replace id in string with the same id plus number?

I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/

jQuery replace hyphens with spans for blogger date header

I'm looking to customize the default date header in blogger with jQuery.
The original output is:
<h2 class='date-header'>2011-01-20</h2>
I want to wrap the YYYY, MM, and DD in spans so I can manipulate them as child nodes.
The result would be:
<h2 class='date-header'><span class="dhy">2011</span><span class="dhm">01</span><span class="dhd">20</span></h2>
Each attempt of mine adds extra tags so it's a nested mess.
Anybody have a good solution?
Here's a nice functional solution:
$('.date-header').html(function() {
var txt = $(this).text();
var classes = ['dhy', 'dhm', 'dhd'];
$(this).html($.map(txt.split(/-/), function(val) {
return $('<span/>', {'class': classes.shift()}).text(val)[0];
}));
});
http://jsfiddle.net/ThiefMaster/WdRAw/
If it always has the same format of YYYY-MM-DD then you could use split to get the elements, loop through them, create your output HTML then add that as the HTML of the h2.
$(function()
{
$(".date-header").each(function()
{
var arrDate = $(this).text().split("-");
var strOut = '<span class="dhy">'+arrDate[0]+'</span>-';
strOut+= '<span class="dhm">'+arrDate[1]+'</span>-';
strOut+= '<span class="dhd">'+arrDate[2]+'</span>';
$(this).html(strOut);
});
});
And a fiddle: http://jsfiddle.net/ahallicks/xGa2J/2/
I think this should do it:
var header = $('.date-header');
var d = header.text().split('-');
header.html('<span class="dhy">' + d[0] + '</span><span class="dhm">' + d[1] + '</span><span class="dhd">' + d[2] + '</span>');

Categories