HTML onload - using variables as parameters - javascript

I want to use something like:
<body onLoad="init('A sentence with "quoted text" as parameter')">
Unfortunately, this does work, as the quotes in the parameter are not treated properly.
Escaping the quotes also does not work
<body onLoad="init('A sentence with \"quoted text\" as parameter')">
(Above also does not work).
How do I deal with this. I though maybe I can create a string variable and assigne my sentence (with quotes) to it. But I dont know how to do it! The body onload is HTML and the Javascript variables would be visible only within the scope of the script, right? To be precise, the following does not work:
<script language="JavaScript">
var dada='A sentence with \"quoted text\" as parameter';
</script>
<body onLoad="init($dada, '</a>')">

You would have to use HTML entities to make it work:
<body onLoad="init('A sentence with "quoted text" as parameter')">
the much cleaner way, though, would be to assign the value in a separate <SCRIPT> part in the document's head.
...
<script>
body.onload = function() { init('A sentence with "quoted text" as parameter'); }
</script>
<body>
...
the onload event has the general downside that it is fired only when the document and all its assets (images, style sheets...) have been loaded. This is where the onDOMLoad event comes in: It fires when the core HTML structure is ready, and all elements are rendered. It is not uniformly supported across browsers, though, so all frameworks have their own implementation of it.
The jQuery version is called .ready().

Rather than inlining the onLoad method, why not set it programatically. You can then use the power of closures to get the data into the function.
<script type="text/javascript">
var data = "some data";
document.body.onload = function()
{
alert(data);
}
</script>

not the nicest way
onload='init("A sentence with \"quoted text\" as parameter")'

By the way, I was making a silly mistake.
<script language="JavaScript">
var dada='A sentence with \"quoted text\" as parameter'; </script>
<body onLoad="init(dada, '</a>')">
This works too. I was using $dada instead of dada in the onload call.

Related

How to encode a JSON string that includes HTML characters?

I have an ASP.NET MVC view model that I need to pass to a JavaScript function when the page loads, and I'm currently doing that like so:
<script type="text/javascript">
$(window).on("load", function () {
myFunction(#Html.Raw(JsonConvert.SerializeObject(Model)));
});
</script>
In other words, I'm using JSON.NET to serialize the model to JSON, and inserting that (un-encoded) into my <script> block.
When rendered, the script block ends up looking something like:
<script type="text/javascript">
$(window).on("load", function () {
myFunction({"myProperty": "the property value"});
});
</script>
That works, up to a point. But when my model contains a string property that whose text includes HTML tags *, these confuse the browser into thinking that the <script> block has ended, and the browser starts rendering the tags embedded in the view model.
Edit: per the comments, this only happens if there's a </script> tag.
For example:
<script type="text/javascript">
$(window).on("load", function () {
myFunction({"myProperty": "<script>...</script>"});
});
</script>
How can I solve this?
This is a know problem. PHP's json_encode function encodes / as \/ to avoid exactly this problem.
A straightforward solution is to write your own JSON encode wrapper-function that replaces </script> by <\/script> after JSON encoding.
Maybe there is a better solution though, I'm not familiar with asp.net.

convert blocks from text/plain to text/javascript and execute it

my problem is as follow.
I have a multiple script blocks that contain javascript code type of text/plain.
So my question is is there any script that i can dynamically convert them from text/plain to text/javascript type and execute its content ? The problem i'm having is the place of execution, because scripts contain document.write so the output is appended in the end of the html not on the location of the script itself.
eg: let's say something like this
<script type="text/plain">alert('hello world');</script>
<script type="text/javascript">
$(document).ready(function(){
$("script[type*=plain]").each(function() {
$(this).attr('type','text/javascript');
});
});
</script>
thnx
Modifying a script element in place doesn't cause it to be executed. You need to create a new script element with the appropriate content. Another option is to eval() the contents of the old element:
$(document).ready(function(){
$("script[type*=plain]").each(function() {
eval($(this).text());
});
});
You can go with some nasty approach, of selecting the tag with type=plain and then accessing its innerText attribute, assigning it to eval method.
var el = $("script[type*=plain]")[0];
eval(el.innerText);
But I'd try to avoid using eval
If there's a different approach I'm not aware of it, and for this I am sorry.
You can not make document.write to place it's output in place of <script> element if you change script's type, because entire page's javascript code woudn't re-run every time you add new <script> or evaluating existing one.
If you want to replace <script type="text/plain"> with the result of script execution, you can return some string from that script instead of using document.write and then insert this string in place of <script type="text/plain"> element:
<script type="text/plain">
var result = "line1<br>";
result += "line2";
alert('hello world');
result
</script>
<script type="text/javascript">
$(document).ready(function(){
$("script[type*=plain]").each(function() {
$(this).replaceWith(eval($(this).text()));
});
});
</script>

Javascript Replace() and innerHTML

I have this code: [it is a rough example with poor coding, but it illustrates what I want to do.]
<html>
<body>
<script type="text/javascript">
function fun()
{
var divs = document.getElementById('hi');
divs.innerHTML = divs.innerHTML.replace("cake","jump");
alert(divs.innerHTML);
}
</script>
<div id="hi">
<span onclick="fun('cake');">Mer<span onclick="fun('cake');">Mer</span></span>
</div>
<a onclick='fun()';)>Click</a>
</body>
</html>
When I click on the <a> i want to change the onclick parameter within fun() from 'cake' to 'jump'. I do not want to use the setAttribute() method as my real example has several nested tags and I want to replace 'cake' in several different places.
I want the innerHTML.replace() function to work to do this but, alas it doesn't function as I want it to. How do I replace text within innerHTML?
Forget it. Never hack around with the innerHTML, there's no guarantee it will be in any particular format, you're very likely to mess up the markup by replacing the wrong thing, and even if it works, you're serialising the document content into a string, hacking it and then recreating the entire content from the string again, instead of just replacing a particular thing you're interested in. This is slow and loses all non-serialisable data (like form field values, JS references and assigned event handlers).
In general DOM methods are much more reliable for altering page content. It's what they were designed for. Use them, and use the DOM Level 1 HTML properties in preference to setAttribute which is badly broken in IE. This goes double for event handler attributes. Trying to hack at JavaScript code inside an attribute value inside an HTML string is insanity, even if it worked.
There is no need whatsoever to replace any page content. You could implement your example much more easily with a simple variable:
<div id="hi">
<span>Mer<span>Mer</span></span>
</div>
<a id="foo">Click</a>
<script type="text/javascript">
var potato= 'cake';
document.getElementById('foo').onclick= function() {
potato= 'jump';
return false;
};
var spans= document.getElementById('hi').getElementsByTagName('span');
for (var i= spans.length; i-->0;) {
spans[i].onclick= function() {
alert(potato); // do whatever with the variable
};
}
</script>
First, you have an error in your HTML:
<a onclick='fun()';)>Click</a>
What's with the ;) outside the attribute value?
Next...
[...] method as my real example has several nested tags and I want to replace 'cake' in several different places.
This means you really, really don't want to use innerHTML and replace(). It will screw up. Use an HTML parser of sorts; walk the DOM recursively... anything other than replace.
Within the scope of your specific example, I suggest using a variable to hold the value of cake and jump instead.
Change your replace call to use the RegEx "global" flag:
divs.innerHTML = divs.innerHTML.replace(/cake/g,"jump");
That said, if you're using this for more than a quick test, you should use DOM objects to accomplish what you would like to do. Otherwise, this will get ugly really fast.
Also, it wouldn't hurt to change your <a> tag code:
<a onclick='fun(); return false;')>Click</a>
(The return false; is optional, but good practice.)
The easiest way to change the onclick parameter is to make it a variable instead of a string literal. Here I'm using a variable called food:
<script type="text/javascript">
var food = "cake";
function change()
{
food = "jump";
}
</script>
<div id="hi">
<span onclick="alert(food);">Mer<span onclick="alert(food);">Mer</span></span>
</div>
<a onclick='change()'>Click</a>

Missing } in XML expression

I have an external javascript file that I want to, upon include, write some HTML to the end of the web page.
Upon doing so though I get the error Missing } in XML expression on the line that uses dropdownhtml.
Here is my code
var dropdownhtml = '<div id="dropdown"></div>';
$(document).ready(function(){
//$(document).append(dropdownhtml);
alert(dropdownhtml);
});
The XHTML webpage that includes this file does so like this:
<script type="text/javascript" src="/web/resources/js/dropdownmenu.js"></script>
Doing either append or alert throws up the same error, what is going wrong?
I got this error because I called an external JavaScript within an existing JavaScript, so ended up with:
<script type="text/javascript">
<script type="text/javascript">
code
</script>
code
</script>
Edit Your update changes the question a bit. :-)
There's nothing wrong with your quoted Javascript or with the script tag that includes it, the problem must lie elsewhere on the page.
The old answer:
If you're including Javascript inside an XML document, you must wrap it up in a CDATA section, or you'll run into trouble like this because the XML parser neither knows nor cares about your Javascript quotes, and instead seems markup (your <div>s in the string).
E.g.:
<foo>
<bar><![CDATA[
var dropdownhtml = '<div id="dropdown"></div>';
$(document).ready(function(){
//$(document).append(dropdownhtml);
alert(dropdownhtml);
});
]]></bar>
</foo>
Naturally you need to ensure that the ]]> sequence never appears in a string (or comment, etc.) your script, but that's quite easy to do (for instance: "Be sure to interrupt the end sequence with a harmless backslash like this: ]]\>; that escape just resolves to > anyway.")
There's definitely a missing ); at the end of your code sample. Don't get where there may be a missing } though.
I have empty script on my page
<script src=""></script>
And this leads to such error

Why Do Developers Split Up <script in JavaScript?

I see so many things like this:
S = "<scr" + "ipt language=\"JavaScript1.2\">\n<!--\n";
Why do they do this, is there an application/browser that messes up if you just use straight "<script>"?
Have a look at this question:
Javascript external script loading strangeness.
Taken from bobince's answer:
To see the problem, look at that top
line in its script element:
<script type="text/javascript">
document.write('<script src="set1.aspx?v=1234"
type="text/javascript"></script>');
</script>
So an HTML parser comes along and sees
the opening <script> tag. Inside
<script>, normal <tag> parsing
is disabled (in SGML terms, the
element has CDATA content). To find
where the script block ends, the HTML
parser looks for the matching
close-tag </script>.
The first one it finds is the one
inside the string literal. An HTML
parser can't know that it's inside a
string literal, because HTML parsers
don't know anything about JavaScript
syntax, they only know about CDATA. So
what you are actually saying is:
<script type="text/javascript">
document.write('<script src="set1.aspx?v=1234"
type="text/javascript">
</script>
That is, an unclosed string literal
and an unfinished function call. These
result in JavaScript errors and the
desired script tag is never written.
A common attempt to solve the problem
is:
document.write('...</scr' + 'ipt>');
This wouldn't explain why it's done in the start tag though.
The more appropriate way to append scripts is to use the DOM.
Create an element of type <script>. See documentation for document.createElement.
Set its attributes (src, type etc.)
Use body.appendChild to add this to the DOM.
This is a much cleaner approach.

Categories

Resources