Hello

In Drupal form, I can have a text field "foo" like this:

$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]

Comments

tdimg’s picture

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:

$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.

phayes’s picture

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?

dwees’s picture

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


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