1

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!

2
  • What does it do exactly? Updates a DIV with the text of 'car' or red car for example? Elaborate a bit more please.... Commented Jun 2, 2011 at 20:36
  • 1
    What is the exact error or symptom? And What does the HTML look like? (The PHP is only relevant if the generated HTML is "wrong"; using this will very easily show what is wrong -- an HTML validator will help where eyes fail.) Commented Jun 2, 2011 at 20:38

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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>";

2 Comments

you don't need the "javascript:" declaration as onclick is already a JS event handle...
@Jamie - Correct, but it won't hurt either. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.