...

View Full Version : JavaScript quotation marks and apostrophes



Taro
05-23-2012, 01:22 AM
Hello,



<button onclick="javascript:document.write('hello');"></button>

<button onclick="javascript:document.write("hello");"></button>

<button onclick='javascript:document.write('hello');'></button>

<button onclick='javascript:document.write("hello");'></button>
Does it matter putting quotation marks or apostrophes when using JavaScript?

Old Pedant
05-23-2012, 01:40 AM
No to JavaScript, assuming they are correctly matched up.

Same answer for HTML.

BUT... But if you embed javascript *in* HTML, then HTML will process the quotes first.

For example, HTML will see the strings I show in red:


<button onclick="javascript:document.write("hello");"></button>

same as if you had written

<button onclick="javascript:document.write("
hello
");"
></button>

So the only code given to javascript will be document.write(

The hello and the ); are then HTML errors, but of course HTML just ignores errors.

NOTE: You can't use document.write to respond to *ANY* human interaction.
NOTE: The use of javscript: like that was deprecated more than 10 years ago.

VIPStephan
05-23-2012, 10:03 AM
For example, HTML will see the strings I show in red:


<button onclick="javascript:document.write("hello");"></button>

same as if you had written

<button onclick="javascript:document.write("
hello
");"
></button>

So the only code given to javascript will be document.write(

The hello and the ); are then HTML errors, but of course HTML just ignores errors.

To expand on that for clarification: for HTML the first double quote is the opening quote of the attribute value and the second double quote it encounters is the closing double quote:


<button onclick="javascript:document.write("hello");"></button>

Since the rest coming after that second double quote isnít a valid attribute itís an error.

Now, you shouldnít write inline JS anyway but itís still good to know that if you do that then you should use alternating single/double quotes, i. e.:


onclick="here comes JS and 'single quotes' should be used inside here"
onclick='here comes JS and "double quotes" should be used inside here'

Old Pedant
05-23-2012, 05:05 PM
Well, I didn't realize we were going to explore this in depth, but since we are...

Don't forget about this:

<input type="button" onclick="alert(&quot;this works, too&quot;)" value="see?"/>

Taro
05-23-2012, 10:05 PM
I appreciate all the suggestions, the development software I have to aid me is probably deprecated itself; but I do understand a tad more about how the double and single quotations/ apostrophes functions.

Philip M
05-24-2012, 11:58 AM
Which is easier to read? alert("iBall's a troll"); or alert('iBall\'s a troll'); :D

Double quotes involve pressing the shift key.

VIPStephan
05-24-2012, 02:55 PM
Double quotes involve pressing the shift key.

So do single quotes for me.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum