Johnathan Au
Johnathan Au

Reputation: 5362

Why doesn't my onclick event handler in Javascript work?

I currently have a button when clicked it should open up a new window but I am getting this error: Uncaught SyntaxError: Unexpected token :. I am using window.open()

$url = "http://www.google.com";
$button .= 
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open('.$url.');"/>';

I have noticed that when I use window.open() with no parameters it works but when I pass in the $url variable all hell breaks loose. I get syntax errors. I've tried http://www.google.com, www.google.com and google.com to no avail!

Thanks for your help in advance!

Upvotes: 0

Views: 688

Answers (3)

Dutchie432
Dutchie432

Reputation: 29160

Because you are missing the single quotes needed to encapsulate the url string.

$url = "http://www.google.com";
$button .= 
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open(\''.$url.'\');"/>';

You're adding a layer of string encapsulation. When you pass a string value to a function it must be in quotes, as it is a string.

doSomething('http://www.ibm.com/');

When you are doing this inline in your html, you need to encapsulate the javascript in double quotes so it becomes

onclick="doSomething('http://www.ibm.com/');"; 

Then, if you want PHP to echo that, or to assign it as variable, you need to enclose all of that in quotes, so you can do

<?php 
    //encapsulate in double quotes and escape double quotes
    echo " onclick=\"doSomething('http://www.ibm.com/');\" "; 

    //encapsulate in single quotes and escape single quotes
    echo ' onclick="doSomething(\'http://www.ibm.com/\'); '; 
 ?>  

Any way you break it down you need have 3 string encapsulations embedded in one another, so you must find a way to differentiate between the quotes used in JS and the quotes used in PHP.

Otherwise you would have a problem.

<?php 

    //Houston We have a problem!
    echo " onclick="doSomething('http://www.ibm.com/');\" "; 
         ^         ^                                    ^ ^
 Open Quote       Close Quote                  Open Quote Close Quote 
 ?>  

Upvotes: 5

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

There are a couple of things wrong here:

You have a period character before the equals, eg

$button .= 

Should be

$button =

And you need to escape your single quotes:

$url = "http://www.google.com";
$button = '<input type="button" value="Print Timetable" class="printButton" onclick="window.open(''.$url.'');"/>';

Upvotes: 1

bitoshi.n
bitoshi.n

Reputation: 2318

I think it suppose to be like this:

$url = "http://www.google.com";
$button .= 
'<input type="button" value="Print Timetable" class="printButton" onclick="window.open("'.$url.'");"/>';

window.open() require quote or double quote

Upvotes: 0

Related Questions