How to properly escape inline javascriptThere are 3 ways to include javascript in your webpages.
1. as an external file <script language='JavaScript' type='text/JavaScript' src='externalfile.js'></script> 2. in the body of your html file <script language='JavaScript' type='text/JavaScript'> alert('code for monkeys'); </script> 3. inline in html <input type="button" value="push me" onclick="alert('code for monkeys');"> Question: How do you call alert when it has singled or double quotes in it? Well in methods 1 and 2 you simply use ', or " example: alert('john\'s code'); alert("john's \"code\""); But what if you want to use inline javascript in html (method 3)? A quick googling of escape quotes in html yields an answer. Use " for " (double quote) and ' for ' (single quote). <input type="button" value="push me1" onclick="alert('john\'s code');"> <input type="button" value="push me2" onclick="alert('john\'s \"code\"');"> demo: Now if we are using PHP to generate our html... it gets even worse trying to escape quotes for php, html and javascript and have everything work out correctly. Use the tag_create() function below to avoid having to code ' and "s everywhere. function tag_create($name,$attributes=array(),$children='') { if (strlen($children)==0) return substr(tag_open($name,$attributes),0,-1)." />";//valid xhtml else return tag_open($name,$attributes).$children.tag_close($name); } function tag_open($name,$attributes=array()) { $h="$name "; foreach($attributes as $a_name=>$a_value) { $r = array('\'','"');//replace $w=array(''','"');//replacewith $h.= strtolower($a_name). "='".str_replace($r, $w, $a_value ) ."' "; } return "<".substr($h,0,-1).">";//-1 gets rid of last space } function tag_close($name) { return "</".$name.">"; } usage: $attributes = array(); $attributes['type']='button'; $attributes['onclick']="alert(\"john's code for monkeys\");"; echo tag_create('input', $attributes); This produces the correct output. It doesn't remove the need for all the escaping, but at least if you escape the php string correctly, the code will automatically take care of the ' and "s. | Related Articles javascript AJAX - Asynchronous Javascript and Xml AJAX Back Button Fix How to properly escape inline javasc... HTML Table Row Highlight Javascript - Drag and Drop Dialog Box Javascript - Objects as Associative ... Javascript Convert Date To String (P... Javascript DHTML Slider Widget Javascript filter search through dat... Parsing XML in Javascript and AJAX php Calculate Script Duration in PHP and... Generate CSV Spreadsheet with PHP Generate PDFs with PHP Generate XLS Spreadsheet files with ... How to properly escape inline javasc... HTML Table Row Highlight PHP - Resize an Image with GD PHP Calculate Duration of MP3 PHP Create Zip file PHP mail Function With Attachments |