function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode(" , /n , "+this.prime.nextPrime()));
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Okay so this is my code I am displaying an array of prime numbers. The issue is that I want each prime number to be on a seperate line but I am unable to do this. I have tried /n and but they have not worked. It is being displayed in a textarea in html. Thank you
You could append a br element:
primes.appendChild(document.createElement('br'));
...although usually the way you'd want to do this would be to put the primes in some kind of element container that you could style appropriately with CSS. A series of divs would automatically stack vertically:
var div = document.createElement('div');
div.appendChild(document.createTextNode(/*...your prime...*/));
primes.appendChild(div);
Two side notes on this line:
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
First, it's almost always best to use function references, not strings, with setTimeout. So:
calcPrimesDelay = setTimeout(calcPrimesLoop, this.delay);
Second, unless you're declaring calcPrimesDelay somewhere you haven't shown, you're falling prey to The Horror of Implicit Globals.
You should use a backslash instead of a forward slash (\n)
EDIT: The below only applies to "normal" elements. For a textarea, you should be doing primes.value += " , \n , "+this.prime.nextPrime();
Additionally, newlines are collapsed in HTML (if you write text on multiple lines in your source code, it comes out on one line) but you can "fix" this using simple CSS:
primes.style.whiteSpace = "pre-wrap";
Spread the word about white-space! People need to stop using <br /> tags just to get a newline!
Related
I have a django template in which my javascript function has the following lines,
resDiv = document.getElementById("res");
console.log(result.des);
resDiv.innerHTML+=('<h3 style="padding-bottom:50px;"><strong>Desciption: </strong><br><br><i style="color:#0B45A4;">'+result.des+'</i></h3>');
When console.log is executed, it is printed along with new lines in result.des.
But when I concatenate it and try try to fill the innerHTML of resDiv the new lines are not being printed.
All new lines are removed and is filled.
How can I make sure that the new lines are printed in resDiv?
Try something like this, and be sure that resDiv is your real target
resDiv.innerHTML = resDiv.innerHTML.concat('<h3 style="padding-bottom:50px;"><strong>Desciption: </strong><br><br><i style="color:#0B45A4;">'+result.des+'</i></h3>');
from your question it is not totally clear, what you mean, but I guess that you just need to replace the newlines in result.des (e.g. \n, \r) with html newlines <br>
When you concatenate your result.des, make sure you put <br> tag between lines.
https://www.w3schools.com/tags/tag_br.asp
If result.des is a javascript array, you can do result.des.join('<br>');
[text area control contains new line break so i should remove that new line break from top and replace with remaining string like image two][1]
This images shows
You could trim it:
$('textarea').val(function(_, val){
return val.trim();
});
But better would be to avoid it server side, before rendering it on client.
Please use jQuery trim() function to remove line breaks. Below code may be help you.
var obj=$("#textareaID");
obj.val(obj.val().trim())
http://live.datatables.net/hucuwemi/1/watch
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Tell me please, what is the sacred power of the style below:
var javascript = new Language(
'Brendan Eich'
, new Date(1995, 0, 1)
, ['C', 'Java', 'Scheme']
);
Why do lots of programmers use that style? What benefits does it have? For example,
var javascript = new Language(
'Brendan Eich',
new Date(1995, 0, 1),
['C', 'Java', 'Scheme']
);
I like much more than previous. Thanks.
Lots of great answers already. Allow me to give you my own one, to make things as clear as possible.
I personally call this way of writing code 'Haskel style', since it's a common style to use in Haskell. Let me give you a Haskell example first:
data Settings = -- The user settings
{ has_sound :: Bool -- Determines if the user has sound
, has_power :: Bool -- Determines if the user has electricity
, has_graphics :: Bool -- Determines if the user has graphics
, user_name :: String -- The name of the user
, user_password :: String -- The hashed password of the user
, user_email :: Email -- The email address of the user
, stylesheet :: Style -- The stylesheet to use
}
And a Javascript snippet from one of my projects:
var events // Holds the events to generate a event handler for.
, var2 // Quick description for var2.
, var3 // Quick description for var3.
, ... // ...
;
events = // Event handlers will be generated for the following events:
[ "onmousedown" // Works outside of the window element
, "onmouseup" // Works outside of the window element
, "onmousemove" // Works outside of the window element
, "onmousewheel" // This will handle DOMMouseScroll aswell
];
Benefits of 'Haskell style'
Easy to read
'Haskell style' takes advantage of the column style layout. This column style makes your code more readable. In fact, it makes your code so much more readable that you use it all the time. Imagine writing code without tabs or leading spaces!
By taking advantage of column style layout, variable names, types, etc. are easier to read aswell. By grouping up variables by prefix, our future reader will easily find what he is looking for, without using a advanced search query.
Easy to document
Column style layout has more advantages. By grouping up our code we can add a column reserved for comments. Now you can read your code without even needing color highlighting, and adding information to your comment is as easy as finding the right column and modifying it.
Besides, this column-like style of documenting your code is pretty much what you get after using a documentation generator like Doxygen, removing the necessity for this kind of tool.
Easy to notice mistakes
Noticing a missing comma is a piece of cake using this style of coding. Simply look for a line that doesn't start with it! On the other side of the spectrum, we have the comma's at the end of the line. We missed one? Nope, because it is the last element, or because the expression continues on the next line.
And finding the first element in a list is as easy as could be. When dealing with long lines, the first element is easily overlooked, but by placing the first element on it's own line and puting a [ or { instead of a , right in front of it, it's easy to spot.
Easily scalable
You might say "But this layout style will get imposible to handle once the expression gets big!", which is quite true, but is this any different for the rest of your code?
I think that by using column style you will at least keep your code readable, which in the long run is worth more than the struggle you might have to fit it into a column layout.
All in one example!
var scalable = // This is a example variable
[
[ new MyObject // This is how I would style Object Allocation
( "11"
, "This is the first element"
, function // This is a very secret function...
( secret // ..with secret..
, variable // ..variable..
, names // ..names!
)
{
// <-- Use spaces, not tabs :)
}
)
, "12"
]
,
[ { id: 21 // Where's 20?
, name: "This is the third element" // It sure is
, func: function() { /* My body feels empty :c */ }
}
, "22" // Notice how 21 is a integer, not a string. Sneaky!
]
];
TL; DR
This style of placing comma's, 'Haskell style', has a couple of advantages:
Easy to read
Easy to document
Easy to notice mistakes
Easily scalable
If you have an extra comma in the end of the last line it will work in some browsers but not in all browsers. Making the error harder to detect than a extra comma at the beginning (which fails on all browsers). And most developers prefer to see the error right away (so they can fix it), instead of risking a production issue for inadvertently not supporting some browsers. Especially if the solution is as easy as removing a comma.
Plus, having the comma at the beginning of the line, make it simpler to add a line at the end and you will have to touch only that line (you will not need to add the comma in the line before). Which is important if you are using version control (e.g. diff, annotate, bisect). Someone can argue that adding a line at beginning of the array or object will need the same extra work of touching 2 lines (if you use commas at the beginning), but in my experience, inserting a line at the beginning is much less likely that inserting a line at the end.
This is because the comma belong to the new line next statement and not the previous one. (As #Dave Newton states it in his comment below: the pseudo-BNF would be foo [, foo]*-ish)
For example:
If you have this:
a,
b,
c
If you need to remove the c then you need to delete two things: de c and the comma on the previous line. If you do this:
a
,b
,c
now you only need to delete the ,c line. It makes more sense this way, because the comma behind the b in the first example only is needed because of the c. It does look worse this way though. It's a trade off between maintainability of your code and the way it looks.
I think it's done so that it's easier to spot a missed comma.
var something = 0,
foo = "a string",
somethingElse = []
bar;
var something = 0
, foo = "a string"
somethingElse = []
, bar;
It is easier to just look at your code to verify you have a comma where needed. If you had to scan the end of each line of code the missing commas wouldn't just jump out like they do when they are lined up on the left hand side.
This offers a little bit of protection in languages which don't accept trailing commas from accidentally introducing syntax errors with trailing commas
In SQL, trailing commas will cause syntax errors. In JavaScript, it will be accepted most places, but will fail with a cryptic error in some Internet Explorer versions, for example.
JS works in most browsers, but fails in some
var thing = {
a: 1,
b: 2,
// trailing comma
c: 3,
};
Syntax error in SQL
SELECT
col1,
col2,
-- Syntax error in SQL
col3,
FROM table
It's one way to make sure you don't forget the comma when adding a new item to a collection, and don't accidentally leave on a trailing comma in collections.
By putting it on the new line it's visually obvious.
I don't care for it, but I understand why people would.
You might be looking at generated code, for instance, when writing a loop to generate an SQL select statement sometimes I will write it like:
sql = "SELECT";
sql += " table.id"; // or some field that will always be in the query
for (var i = 0; i < 10; i++;) {
sql += ", table.field" + i;
}
sql += "FROM table" // etc
Instead of adding the comma at the end and then having a condition to omit it on the last iteration of the loop or doing:
sql = "SELECT";
for (var i = 0; i < 10; i++;) {
sql += " table.field" + i + ",";
}
sql += " table.id";
sql += "FROM table" // etc
Which is functionally equivalent, but then the ID doesn't appear where I usually want it.
Maybe because removing or adding line and its commas is simpler with second example
We're writing a web app that relies on Javascript/jQuery. It involves users filling out individual words in a large block of text, kind of like Mad Libs. We've created a sort of HTML format that we use to write the large block of text, which we then manipulate with jQuery as the user fills it out.
Part of a block of text might look like this:
<span class="fillmeout">This is a test of the <span>NOUN</span> Broadcast System.</span>
Given that markup, I need to separately retrieve and manipulate the text before and after the inner <span>; we're calling those the "prefix" and "suffix".
I know that you can't parse HTML with simple string manipulation, but I tried anyway; I tried using split() on the <span> and </span> tags. It seemed simple enough. Unfortunately, Internet Explorer casts all HTML tags to uppercase, so that technique fails. I could write a special case, but the error has taught me to do this the right way.
I know I could simply use extra HTML tags to manually denote the prefix and suffix, but that seems ugly and redundant; I'd like to keep our markup format as lean and readable and writable as possible.
I've looked through the jQuery docs, and can't find a function that does exactly what I need. There are all sorts of functions to add stuff before and after and around and inside elements, but none that I can find to retrieve what's already there. I could remove the inner <span>, but then I don't know how I can tell what came before the deleted element apart from what came after it.
Is there a "right" way to do what I'm trying to do?
With simple string manipulations you can also use Regex.
That should solve your problem.
var array = $('.fillmeout').html().split(/<\/?span>/i);
Use your jQuery API! $('.fillmeout').children() and then you can manipulate that element as required.
http://api.jquery.com/children/
For completeness, I thought I should point out that the cleanest answer is to put the prefix and suffix text in it's own <span> like this and then you can use jQuery selectors and methods to directly access the desired text:
<span class="fillmeout">
<span class="prefix">This is a test of the </span>
<span>NOUN</span>
<span class="suffix"> Broadcast System.</span>
</span>
Then, the code would be as simple as:
var fillme = $(".fillmeout").eq(0);
var prefix = fillme.find(".prefix").text();
var suffix = fillme.find(".suffix").text();
FYI, I would not call this level of simplicity "ugly and redundant" as you theorized. You're using HTML markup to delineate the text into separate elements that you want to separately access. That's just smart, not redundant.
By way of analogy, imagine you have toys of three separate colors (red, white and blue) and they are initially organized by color and you know that sometime in the future you are going to need to have them separated by color again. You also have three boxes to store them in. You can either put them all in one box now and manually sort them out by color again later or you can just take the already separated colors and put them each into their own box so there's no separation work to do later. Which is easier? Which is smarter?
HTML elements are like the boxes. They are containers for your text. If you want the text separated out in the future, you might as well put each piece of text into it's own named container so it's easy to access just that piece of text in the future.
Several of these answers almost got me what I needed, but in the end I found a function not mentioned here: .contents(). It returns an array of all child nodes, including text nodes, that I can then iterate over (recursively if needed) to find what I need.
I'm not sure if this is the 'right' way either, but you could replace the SPANs with an element you could consistently split the string on:
jQuery('.fillmeout span').replaceWith('|');
http://api.jquery.com/replaceWith/
http://jsfiddle.net/mdarnell/P24se/
You could use
$('.fillmeout span').get(0).previousSibling.textContent
$('.fillmeout span').get(0).nextSibling.textContent
This works in IE9, but sadly not in IE versions smaller than 9.
Based on your example, you could use your target as a delimiter to split the sentence.
var str = $('.fillmeout').html();
str = str.split('<span>NOUN</span>');
This would return an array of ["This is a test of the ", " Broadcast System."]. Here's a jsFiddle example.
You could just use the nextSibling and previousSibling native JavaScript (coupled with jQuery selectors):
$('.fillmeout span').each(
function(){
var prefix = this.previousSibling.nodeValue,
suffix = this.nextSibling.nodeValue;
});
JS Fiddle proof of concept.
References:
each().
node.nextSibling.
node.previousSibling.
If you want to use the DOM instead of parsing the HTML yourself and you can't put the desired text in it's own elements, then you will need to look through the DOM for text nodes and find the text nodes before and after the span tag.
jQuery isn't a whole lot of help when dealing with text nodes instead of element nodes so the work is mostly done in plain javascript like this:
$(".fillmeout").each(function() {
var node = this.firstChild, prefix = "", suffix = "", foundSpan = false;
while (node) {
if (node.nodeType == 3) {
// if text node
if (!foundSpan) {
prefix += node.nodeValue;
} else {
suffix += node.nodeValue;
}
} else if (node.nodeType == 1 && node.tagName == "SPAN") {
// if element and span tag
foundSpan = true;
}
node = node.nextSibling;
}
// here prefix and suffix are the text before and after the first
// <span> tag in the HTML
// You can do with them what you want here
});
Note: This code does not assume that all text before the span is located in one text node and one text node only. It might be, but it also might not be so it collates all the text nodes together that are before and after the span tag. The code would be simpler if you could just reference one text node on each side, but it isn't 100% certain that that is a safe assumption.
This code also handles the case where there is no text before or after the span.
You can see it work here: http://jsfiddle.net/jfriend00/P9YQ6/
I have the following being extracted from an XML and being put into a jQuery variable.
links.append($("<a href='"+alink+"'></a> ").html(desc));
...however the does not output onto the page. I need this to separate the hrefs on output
I have also tried
links.append($("<a href='"+alink+"'></a>").html(desc));
links.append($(" "));
Many thanks!
$("<a href='"+alink+"'></a> ")
Yeah, that's actually only creating the <a> element, and discarding the nbsp. When you pass a string into the $() function that looks like(*) HTML, jQuery creates the stretch of markup between the first < in the string and the last >. If you've got any leading or trailing content outside those, it gets thrown away(**). You could fool jQuery by saying:
$("<a href='"+alink+"'></a> <!-- don't ignore me! -->")
This doesn't seem to be documented anywhere, makes no sense whatsoever, and might be considered a bug, but it has been jQuery's normal behaviour for some time so it's probably not going away.
When you pass an HTML string to the append function (and other manipulation methods) directly instead of via the $ function, this behaviour does not occur. So:
links.append("<a href='"+alink+"'></a> ");
actually does keep the space. But a better way forward is to stop throwing HTML strings about, so you don't have to worry about alink containing ', < or & characters either, and work in a more DOM style:
var link= $('<a/>');
link.attr('href', alink);
link.html(desc);
links.append(link);
links.append('\xA0');
Or, more concisely, using jQuery 1.4's props argument shortcut:
links.append($('<a/>', {href: alink, html: desc}));
links.append('\xA0');
assuming that desc is really something that should contain HTML markup; if not, use text instead.
(I used \xA0, the JavaScript string literal way to include a character U+00A0 NON-BREAKING SPACE as it is a whole two characters shorter than the HTML entity reference. Woohoo!)
(*: how does it tell that a string is HTML? Why, by checking to see if there's a < and > character in it, in that order, of course. Meaning it'll get fooled if you try to use a selector that has those characters in. Brilliant, jQuery, brilliant.(***))
(**: why? see line 125 of jQuery 1.4.2. It builds the HTML fragment from match[1]—the group from the first < to the last > in quickExpr—and not the original string or match[0].)
(***: I'm being sarcastic. The insane over-overloading of the $ function is one of jQuery's worst features.)
You better style with css, something like :
links.append($("<a class='link' href='"+alink+"'></a>").html(desc));
in css :
a.link {
padding-left : 5px ;
padding-right : 5px ;
}
you could try