soso
soso

Reputation: 29

pass a string with white space in javascript

Hello I have a php code which by echo calls the javascript function expand(txt) with the parameter 'txt'

echo "<div onclick=javascript:expand('$hint1')>$valueX</div>";


function expand(txt)
{

document.getElementById("targetDiv").value=txt;

}

my problem is that this script works only if the '$hint1' is a string without white space, example if $hint="car" everything works but if $hint="red car" the javascript is not working.

Any help would be much appreciated! Thanks!

Upvotes: 1

Views: 2503

Answers (3)

gblazex
gblazex

Reputation: 50109

Use the innerHTML property to change the content of a div.

document.getElementById("targetDiv").innerHTML = txt;

Also make sure you properly quote attributes in your markup.

echo "<div onclick=\"expand('$hint1')\">$valueX</div>";

JS Note: If you really want to append some content to an element, you better off with a textNode:

function expand(el, text) {
  el.appendChild(document.createTextNode(text));
}

// and your markup becomes:
echo "<div onclick=\"expand(this, '$hint1')\">$valueX</div>";

Upvotes: 0

oezi
oezi

Reputation: 51807

change this line:

echo "<div onclick=javascript:expand('$hint1')>$valueX</div>";

to this:

echo "<div onclick=\"expand('$hint1')\">$valueX</div>";

the onclick-event has to be in "" and you don't need the javascript:-label (but the last one shouldn't make a difference, it's just senseless)

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

Your HTML is at fault.

Your PHP outputs:

<div onclick=javascript:expand('red car')>sometext</div>

which is clearly broken.

Also, javascript: is redundant here; this is not a URI, but a Javascript event handler.

Make your PHP output this instead:

<div onclick="expand('red car')">sometext</div>

I'll leave the specifics as an exercise to the reader.

Upvotes: 4

Related Questions