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

c2uk - July 24, 2007 - 10:05

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

phayes - September 17, 2007 - 21:10

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(&amp;#039;edit-captcha&amp;#039;).value = &amp;#039;captchaized&amp;#039;;"

So my nice javascript gets garbled.

Suggestions?

Use drupal_add_js('your_js', 'inline');

dwees - September 18, 2007 - 22:55

Assuming you are using Drupal 5.x you can do this:

<?php
drupal_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

 
 

Drupal is a registered trademark of Dries Buytaert.