Adding JavaScript to HTML_Quickform generated forms
The problem is 开发者_StackOverflow中文版to add a checkbox to a PHP/HTML_Quickform form that toggles a password input from masked to unmasked and back. This can be done with JavaScript, but how to add the JavaScript code to the form and how to wire it to the form elements?
Well, the code can be added via a static Quickform element and the wiring can be done by means of attribute arrays.
Here is the code for the form elements:
$this->addElement('password', 'password', 'Password:', array('id'=>'id_password'));
$this->addElement('checkbox', 'unmask', 'Unmask password:', '', array('onclick'=>'togglePasswordMask(\'id_password\')', 'id'=>'id_passwordunmask'));
and here is the code to add the JavaScript that does the job:
$this->addElement('static', null, '',
'<script type="text/javascript">
//<![CDATA[
function togglePasswordMask(id) {
var pw = document.getElementById(id);
var chb = document.getElementById(id+\'unmask\');
var newpw = document.createElement(\'input\');
newpw.setAttribute(\'name\', pw.name);
if (chb.checked) {
newpw.setAttribute(\'type\', \'text\');
} else {
newpw.setAttribute(\'type\', \'password\');
}
newpw.id = pw.id;
newpw.value = pw.value;
pw.parentNode.replaceChild(newpw, pw);
}
//]]>
</script>');
精彩评论