TransWikia.com

Webform onchange added with hook_form_id_alter

Drupal Answers Asked by Richard Luckhurst on December 25, 2020

I have a webform on a Drupal 7 site I am working on with a form ID of 144. I have a module that alters this form to add default values to the fields within the webform. This is all working fine. I now have to add an onchange event to one of the textfields.

This is the code I am trying in the module to add the onchange event

$form['submitted']['postal_code']['#attributes']['onchange'] = 'getaddress(this)';

I have a copy of the webform template in my theme directory called

webform-form-144.tpl.php

At the bottom of this template I have the following

drupal_add_js(path_to_theme() .'/js/webform144.js');

to add in a JS file that will have the function to be called by the onchange event. At the moment all I have in the JS file is

function getaddress(code) {
    alert(code);
}

The textfield renders as follows

<input type="text" maxlength="128" size="64" value="408600" name="submitted[postal_code]" id="edit-submitted-postal-code" class="form-control form-text required" onchange="getaddress(this)" required="required">

To me this looks like the getaddress function should be called with the current value of the field when the onchange event fires

I have cleared the Drupal caches. When I try to change anything in the postal_code field nothing is happening so it looks like the onchange event is not firing. I am usinjg the Firefox console and am seeing no evidence of the onchange firing. I am also not seeing the JS alert with the value.

Am I missing something obvious? This is the first time I have tried to add an event to a webform field and I have been unable to find any examples or tutorials that are what I seem to be wanting

Regards

Richard

One Answer

"this" never means a value. "this" always means an object - in this case, "this" means "input" object.

So, in getaddress() function, you must have: alert(code.value);

Answered by Jii on December 25, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP