views:

31

answers:

4

Hi,

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>')">
+2  A: 

You would have to use HTML entities to make it work:

<body onLoad="init('A sentence with &quot;quoted text&quot; 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().

Pekka
NICE ONE +3000!
Luca Matteis
Thanks much. Am a beginner in javascript so missed such alternative styles.
JP19
@JP19 I had an error in the second block. If you use the code, make sure you copy over the change (The additional `function() { }`). Sorry.
Pekka
+1  A: 

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>
Greg B
Thanks, yes this looks good. Amd glad my question got solved so quickly.
JP19
A: 

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.

JP19
A: 

not the nicest way

onload='init("A sentence with \"quoted text\" as parameter")'

Grumpy
This doesnt work, as I mentioned in the question. Thanks though!
JP19
quotes placed different, this does work, i tested it for you
Grumpy