JavaScript innerHTML - javascript

Why doesn't this work? innerHTML cannot take in something so complicated?
<html>
<head>
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td><label for="name">Name:</label></td><td><input type="text" id="name"></input></td></tr>"; +
"<tr><td><label for="remarks">Remarks:</label></td><td><input type="text" id="remarks"></input></td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>
Something less complicated like this works:
var html = "<table><tr><td>123</td><td>456</td></tr></table>";

You need to either escape double quotes within the string you're assigning to the html variable, or just enclose the string with single quotes. Use a text editor with syntax highlighting and errors like that will jump out at you right away. You also have an extra semicolon in your assignment.

Your quoting is broken. You are using double quotes inside the string:
"<tr><td><label for="remarks">Remarks:</label></td><td><input ....
the Firefox error console should always be your first stop, errors like that are always logged there.

Your string is delimited using double quotes and also uses them within the string. Switch to using single quotes within the string.
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>"; +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";

instead of double quotes use single quotes as shown below:
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>' +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";
Enjoy coding!!

You need to either escape double quotes or use single quotes within the string destined for that innerHTML.

There is an error in your string , try this :
var html = "Name:"; +
"Remarks:";
document.getElementById("addtable").innerHTML = html;

Related

How can I render html code in a div using Javascript or jQuery

I'm trying to render some HTML on the fly in my website without success. I've tried using jQuery's .html() function as below:
My html
<div id='open_ender_output'></div>
My JQuery
var openEnderContent = "<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
//openEnderContent comes from my backend
$('#open_ender_output').html(openEnderContent)
The result is
<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>
Is there a way to make the browser render that result on the fly so it reflects the specific styles set on the text?
Decode the content by creating a temporary element.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').html(
// create an element where the html content as the string
$('<div/>', {
html: openEnderContent
// get text content from element for decoded text
}).text()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
Or you need to use a string which contains unescaped symbols.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
You're on the right track. You need to differentiate between single and double quotes when creating a string. You're closing your string by adding double quotes inside double quotes.
Use the var below.
var openEnderContent = "<span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>";
$('#open_ender_output').html(openEnderContent);
Fiddle for example: https://jsfiddle.net/acr2xg6u/
Change your jQuery to
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
Parsing problem from what I can tell.
"<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
You cannot create strings like that. If you are inside one, you must use the other:
"My name is 'Josh Crowe'"
'My name is "Josh Crowe"'
Here's corrected code:
"<p><span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>"

Quotes issue in Javascript

I want to refresh an img element within a div every 5 seconds that would indicate whether the user is connected to the internet or not connected. If the user is connected, it will display an image online, but if the user is offline, a local image will display.
However, I cannot get around this quote problem. I even tried the "&-quot;" thing (without the dash) and it still will not work. Here is the code:
<script type="text/javascript">
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
document.getElementById("test").innerHTML = "<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">";
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>
I do not have the desire to use jQuery or Ajax or any server-side languages because this is all on a local machine.
You can escape those double quotes like this:
document.getElementById("this").innerHTML = "<img id=\"this\" src=\"http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png\" onerror=\"this.src='nowifi.png'\">";
By typing \" you're telling the JavaScript that you want to insert a double quote inside your string. The other option you have is to use single quotes instead. (I've changed your getElementById from 'test' to 'this' since your HTML has no 'test' as Id)
Also, you shouldn't call a function using a string as you did on refreshDiv. Instead you should call its name like this:
window.setInterval(refreshDiv, 5000);
You should use a hierarchy of single quotes and double quotes. Using double quotes under double quotes makes the JS think is a combination of strings. But it fails without the operators.
<script type="text/javascript">
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
document.getElementById("test").innerHTML = '<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">';
}
</script>
<div id=wifi>
<img id="this" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="this.src='nowifi.png'">
</div>
Apart from that rather than checking every 5 seconds I would suggest going and using online and offline events of browser - which then saves your code from having setInterval kind of stuff.
In JavaScript, you can use single-quotes or double-quotes. For your case, you should put the string containing the div in single-quotes and have the HTML attributes within that string using double-quotes. However, it looks like you have a few other mistakes in your code anyway. Try this:
<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png" onerror="error">
with the following in your Javascript:
var theImage = document.getElementById('image');
function error() {
theImage.src='nowifi.png';
}
function refreshDiv(){
theImage.innerHTML = '<img id="image" src="http://stallionware.weebly.com/uploads/3/0/4/3/30431988/4901948_orig.png"
onerror="error">';
}
setInterval(refreshDiv, 5000);

Replace all html attribute definitions that use single quotes with double quotes

I have an html string and I want to replace any instance of an html attribute being set with single quotes with double quotes.
So for example, I want to replace
<script src='foo.js'></script>
with
<script src="foo.js"></script>
However, I want to do this without affecting any single quotes that might be in javascript statements or in text within the html.
Eg
<script> var foo = '67'; </script>
should be unaffected and
<div id='foo'> 'hi' </div>
should become
<div id="foo"> 'hi' </div>
Is there any easy way to do this?
For a given element selecting it with jquery and then reading its outerHTML does this but I want to do it to an entire page of html all at once.
Thanks!
Try this:
var str = "<br style = 'width:100px'/> test link";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
You can refector it to strictly match your case.
Answering my own question as I think the easiest solution to this is what is shown in this fiddle and does not require jquery or regexps:
http://jsfiddle.net/QdUR5/1/
<html id="foo"></html>​
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
​
Basically you just need to set the inner html of an html element to the html string without the html tags and then output the html elements outer html.
I think that is a bit simpler than using a regexp although that is an awesome regexp Mike :)

How to escape a single quote in jQuery?

I know I can use \', but that's not the point here. Let's say I have the word "can't". It has "'" in it now. This goes in to a var in a function like so:
function active(id,clas,match,hometeam,awayteam){
So let’s say hometeam has the value of "can't". When I try to use this code:
$('#test').html(hometeam + " VS " + awayteam);
It's not working, because essentially it has:
$('#test').html(can't + " VS " + awayteam);
How do I solve this?
EDIT:
I think the problem is not in the jQuery. The line that calls this function is this line:
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','match1','hometeam','awayteam')" />
So how do I escape this?
EDIT: I haven't found the perfect solution, so I just changed the word in my database and added the "\" for now...
This should work. If the contents have double quotes then wrap the string in single quotes and escape single quotes inside.
var hometeam = '"can\'t"';
$('#test').html(hometeam + 'VS' + awayteam)
The values returned by variables do not need to be escaped in javascript. If you are having a problem there is some other underlying issue.
EDIT: Per your question edit you will need to escape the value in the function call, if you were to use can't as one of your parameters you would need
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','can\'t','hometeam','awayteam')" />
The problem is that you are using string operations to build HTML. Use jQuery/DOM methods instead and you won't have issues with this.
Another way would be escaping the quotes but compared to the previous suggestion that's just really ugly.
Since you are creating the HTML in PHP, do something like this:
echo '<input type="button" id="btn" value="1.4" class="butta" onmousedown=\'active("btn","buttdowna","match1",'.htmlspecialchars(json_encode($foo)).', '.htmlspecialchars(json_encode($bar)).');\' />';
You can change the HTML Part like this it will work,
<input type="button" id="btn" value="1.4" class="butta" onmousedown=active("btn","buttdowna","match1","can't","awayteam") />
In an HTML attribute without Quotation also work. Quotation is used to group. Example) title="Click Event" will work and title=Click Event will take the first value(Click) only. That is if a word doesn't contains space then no need of Quotation.

Passing rendered html to a javascript function

I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'

Categories