So,I have a problem with writing some text(h2) with new line,I created the new line by '\n'.It writes it right into the console,but as h2 element it writes it in one line.
Code :
<h2 id="T4"></h2>
<script type="text/javascript">
var TEST = 'a' + '\n' + 'b'
console.log(TEST)
document.getElementById("T4").innerHTML = TEST
</script>
You need to use the HTML special line break tag <br/> like this:
<h2 id="T4"></h2>
<script type="text/javascript">
var TEST = 'a' + '<br/>' + 'b'
console.log(TEST)
document.getElementById("T4").innerHTML = TEST
</script>
Related
In my mongoDB:
description: "Test\n\nTest"
When I try to show it in my ejs file the text ignores de "\n"
Test Test
My HTML
<div id="description">
<%= test.description %>
</div>
I tried to fix this using this code:
var desc = $('#description').text();
desc.replace("\n", "<br>");
$('.description').text(desc);
Also tried:
desc.replace(/(?:\r\n|\r|\n)/g, '<br />');
and:
desc.split("\n").join("<br />");
None of this worked
If I print var desc = $('#description').text(); in the Chrome console, it shows this:
Test
Test
What I'm doing wrong and how do i fix this?
Use html() instead of text() as you want to change the HTML markup....text() will ignore the <br> tags
Also you are just replacing the value not updating it.....need to put the replaced value in the desc variable by
desc = desc.replace(/\n/g, "<br>");
Also desc.replace("\n", "<br>"); will just replace the first \n match
Stack Snippet
var desc = "Test\n\nTest"
desc = desc.replace(/\n/g, "<br>");
$('#description').html(desc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="description"></div>
Using your code, desc.split("\n").join("<br />"); works fine for me.
var desc = $('#description').text();
console.log("original text = " + desc);
desc = desc.split("\n").join("<br />");
console.log("using split/join = " + desc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="description">
Here is
the contents of
the div
with line breaks in it.
</div>
Apologies, I know there are a number of questions along the same lines and they've helped me a lot but I'm still falling at the final hurdle.
I'm trying to dynamically add some jQuery into a div using this:
function displayPage(position,page){
// position arrives looking something like '#pageW20' - ignore quotes
// page arrives looking something like 'pages/benefits.html' - ignore quotes
var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
var str = "<script type='text/javascript'>";
/* Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script>
*/
str += '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()})';
str += '<';
str += '/script>';
alert(str); // Works to here, alert churns out expected output.
//$('"' + position + '"').append(str); // Tried this, end up with syntax error
myDiv.appendChild(str); // This gives Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
}
The last two lines show the errors I'm getting trying 2 different methods. Any clues.
Thanks appreciate your interest.
Update: Here's what I get in my console at the alert() stage which is what I was hoping for -
<script type='text/javascript'>$( "#pageW20" ).load("pages/work.html", function(){openLetter()})</script>
Update: Now solved, thanks #gaetano. My code now looks like:
function displayPage(position,page){
var pos = position.substring(1);
var myDiv = document.getElementById(pos);
myDiv.innerHTML=""; // Remove existing div content
/* Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script>
*/
var str = '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()});';
console.log(str);
var s = document.createElement('script');
s.type = 'text/javascript';
s.text = str;
myDiv.appendChild(s);
}
I cannot understand why you are trying to create and append a script on the fly like described in the comments.
The error you get is:
myDiv.appendChild(str);
But appendChild requires as first parameter a node.
So if you need to continue in this direction you have to create a script node element and after you can append it to the html like in my example:
function displayPage(position, page) {
var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
var str = '$( ' + '"' + position + '"' + ' ).load("' + page + '", function(){openLetter()})';
var s = document.createElement('script');
s.type = 'text/javascript';
s.text = str;
myDiv.appendChild(s);
}
displayPage('_XXX', 'page');
console.log(document.getElementById('XXX').outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="XXX"></div>
The str variable you're passing isn't a Node, it's a String. Try first using:
var line = document.createElement("p");
line.innerHTML = str;
myDiv.appendChild(line);
I'm trying to pass an email address from an HTML form into a javascript snippet to pass to another program.
Form input:
<input name="email" placeholder="Enter Email Address Here" type="email" required="required" id="email_input">
Here's an example of what I'm looking for, note the quotes. In order for the email to pass, it must be within quotes.
<script type="text/javascript">
test({
email: "example#example.com",
});
</script>
Here's what I've tried:
<script type="text/javascript">
test({
email: "document.getElementById("email_input");",
});
</script>
If I'm using a static value like example#example.com, everything works as expected. I'm not able to figure out how to pass the value from the email input field to the "email:" javascript and have it pass though.
Heres what I need: What I have in there document.getElementById("email_input"); is not working, what should this be?
I'm know I'm missing something simple here, just not sure what.
Thanks in advance!
If you're just trying to pass the value of the email input using that test object, this is what you need.
var emailString = document.getElementById("email_input").value;
test({
email: emailString,
});
</script>
You want to grab the value of the input first, and then pass it as a string (assuming you need a string from your first example)
There is two way to get a string from an other typeof element (DOM element, Number, Array, ...) :
<script type="text/javascript">
var elmt = document.getElementById("email_input");
var str1 = elmt.toString();
var str2 = elmt + "";
// alert(str1); and alert(str2) will pop the same result : a string of elmt
</script>
so if you want the entire input as a string you should do :
<script type="text/javascript">
test({
email: document.getElementById("email_input") + ''
});
</script>
if you just want the input value as a string (so the email) you should do :
<script type="text/javascript">
test({
email: document.getElementById("email_input").value + ''
});
</script>
and if you really need to add quotes to a string you also can do :
<script type="text/javascript">
var str= "this is my string";
var withquote= ' " ' + str + ' " ';
//both of the var return a string but one will have a quote and the other won't
alert(str); // pop: this is my string
alert(withquote); // pop "this is my string"
</script>
So in your case :
if you want the entire input as a string with quotes you should do :
<script type="text/javascript">
test({
email: ' " ' + document.getElementById("email_input") + ' " '
});
</script>
if you just want the input value as a string (so the email) with quotes you should do :
<script type="text/javascript">
test({
email: ' " ' + document.getElementById("email_input").value + ' " '
});
</script>
hope I've made myself clear
Feel free to ask if I'm not
have a good one
I want to pull from a tumblr blog and display it on another webpage using javascript.
I'm using the $TUMBLR_BLOG/api/read/json feed which provides a variable filled with the information from the blog post.
I want to print everything up to the "<!-- more -->" set of characters in the 'regular-body' section, ie. I don't want to print everything in the 'regular-body' just up to that more section.
Any thoughts on how to do that?
Eg. API read: http://blog.intercut.yegfilm.ca/api/read/json
Eg. Basic code I'm using:
<script type="text/javascript" src="http://blog.intercut.yegfilm.ca/api/read/json"></script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
document.write(
'<h3> ' + tumblr_api_read.posts[0]['regular-title'] + '</h3>' +
tumblr_api_read.posts[0]['regular-body']);
</script>
<script type="text/javascript">
// The variable "tumblr_api_read" is now set.
var url = tumblr_api_read.posts[0]['url'];
var title = tumblr_api_read.posts[0]['regular-title'];
var body = tumblr_api_read.posts[0]['regular-body'];
body = body.substring(0,body.indexOf("<!-- more -->"));
document.write('<h3> ' + title + '</h3>' + body);
</script>
Simple as that :)
Something like responseData.split("<!-- more -->")[0] ?
Get the index of the <!-- more --> and print the substring upto that index.
sampleString = "Foo <!-- more --> Bar";
moreIndex = sampleString.indexOf("<!-- more -->");
if (moreIndex > 0) {
console.log(sampleString.substring(0, moreIndex));
}
JSFiddle
Use the javascript SubString() method:
Example:
var mystring = 'Hello World <!-- more -->';
alert(mystring.substring(0,mystring.indexOf("<!-- more -->")));
jsFiddle: http://jsfiddle.net/8CXd8/
Documentation: http://www.w3schools.com/jsref/jsref_substring.asp
I'm trying to add a piece of javascript code to a certain <div>.
I enclosed the code in pre and code tags, but when I actually run this the code gets executed. Obviously, that's not what I want at all.
var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
code = code + '<script type="text/javascript">\n';
code = code + '\tadimp.id = ' + 1 + ';\n';
code = code + '\tadimp.type = ' + 1 + ';\n';
code = code + '\tadimp.generate();\n';
code = code + '<\/script></code></pre>';
$("#code").html(code);
You should use < and > for < and > in this case. Try this
var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
code = code + '<script type="text/javascript">\n';
code = code + '\tadimp.id = ' + 1 + ';\n';
code = code + '\tadimp.type = ' + 1 + ';\n';
code = code + '\tadimp.generate();\n';
code = code + '<\/script></code></pre>';
$("#code").html(code);
Surprise! You just manufactured your own XSS vulnerability. Always HTML-encode any data you put into HTML. ("data" is anything you want to appear on screen.)
In the HTML DOM this is thankfully completely automatic. Just use the text property, not the HTML property.
var code = [
'<script type="text/javascript" src="http://source.com/test.js"><\/script>',
'<script type="text/javascript">',
'\tadimp.id = ' + 1 + ';',
'\tadimp.type = ' + 1 + ';',
'\tadimp.generate();',
'<\/script>'
].join('\n');
$('#code').text(code);
// --------^^^^
Live demo: http://jsfiddle.net/6qdBD/3/
Pre tags format the text not necessarily keep what the text within them from being executed as html. Or in this case JavaScript. A better method would be to replace < and > with the html entities < and >.
Instead of using the < and > symbols use < and >
var code = '<script type="text/javascript" src="http://source.com/test.js"></script>\n'
I suggest to just simply replace the < in <script tag to '< and at the end to '>.
Since HTML tags are permitted inside PRE, you cannot just "insert" a text file into an HTML document by slapping <PRE> and </PRE> around them. You have to convert the &, < and > characters into entities first.
From http://htmlhelp.com/reference/wilbur/block/pre.html