Form and JavaScript
johnhelen - July 24, 2007 - 09:27
Hello
In Drupal form, I can have a text field "foo" like this:
<?php
$form['foo'] = array(
'#type' => 'textfield',
'#title' => t('bar'),
'#default_value' => $object['foo'],
);
?>Now I want to use JavaScript so that I can have event such as "onkeyup" event for this textfield
In normal Html, I can do something like
<input name=foo type="text" onkeyup="change(this)"
..../>However, I donot know how to do this in Drupal form
Do you know any tutorial to do this - I am new with Drupal
Many thanks
john
[moved to support]

#attributes is the way to achieve this
Have a look at http://api.drupal.org/api/5/file/developer/topics/forms_api_reference.ht...
#attributes is expecting an array so with your example it should look like this:
<?php$form['foo'] = array(
'#type' => 'textfield',
'#title' => t('bar'),
'#default_value' => $object['foo'],
'#attributes' => array ('onkeyup' => 'change(this)'),
);
?>
But I've never used attributes for Javascript myself, just for adding a class.
Almost, but not quite
I'm having a similar problem. I want a form to call a javascript function when it submits, so I use the onsubmit attribute like so:
$form['#attributes'] = array('onsubmit' => "document.getElementById('edit-captcha').value = 'captchaized';");However, when it's printed, the single quotes are escaped like so:
onsubmit="document.getElementById(&#039;edit-captcha&#039;).value = &#039;captchaized&#039;;"So my nice javascript gets garbled.
Suggestions?
Use drupal_add_js('your_js', 'inline');
Assuming you are using Drupal 5.x you can do this:
<?phpdrupal_add_js("
$(document).ready(function () {
$('#your_form_id').submit(function () {
$('#edit-captcha').val(captchaized());
});
});", "inline");
?>
which should add the function you want on page load. I haven't tested this, but have done similar things using the jQuery JavaScript library.
Dave
My site: http://www.unitorganizer.com/myblog
Might want to try this module.
Javascript validator module
Vision Media
Free Photoshop Downloads
CSS Doc