Javascript encoding
Very handy when you have PHP writing out Javascript code that could contain user-entered data (like carriage returns). It will look ugly in the source view, but it works great.
// see http://www.the-art-of-web.com/javascript/escape/
function js_encode($str) {
$new_str = '';;
for($i = 0; $i < strlen($str); $i++) {
$val = ord(substr($str, $i, 1));
$prefix = $val < 16 ? '\\x0' : '\\x';
$new_str .= $prefix . dechex($val);
}
return $new_str;
}
Overriding an event handler programmatically
Say you already have this somewhere, and want an
onsubmit() handler, and can't change it...
<FORM method="POST" id="the_form" name="the_form" enctype="multipart/form-data" action="<?= $url ?>">
You can do this:
el = document.getElementById("the_form");
el.onsubmit=function() { return check_submit(this);}
Trick: checkboxes in JS and HTML
Thanks to IndyBob
here
To make multiple checkboxes appear in the POST results, you must declare them in this array notation:
<INPUT TYPE="CHECKBOX" name="choice[]" value="<?=$k?>"><?=$c->radio_tag?></INPUT>
To read these in JS, do this:
// check to see if any are picked
for (var i = 0; i < document.the_form.elements['choice[]'].length; i++)
{ if (document.the_form.elements['choice[]'][i].checked)
{ picked = true;
break;
}
}
--
MattWalsh - 14 Sep 2009