Skip to main content

How to add custom javascript into the drupal webform module <form> <submit>

Recently, one of our clients asked to have custom tracking code implemented into their form submissions.

Since the client's site is built on Drupal, all forms are dynamically generated using the Webform module.

Their marketing company instructed us to add an 'onclick' code to :

<input type="submit" class="form-submit" value="Receive Coupons" id="edit-submit" name="op" onclick=tracking("track_submit_quote") />

However, since the Webform module creates all forms dynamically, there was no convenient way of hard coding the code into the form... i.e. there was no way for this to be done via webform admin.

Nevertheless, after some research, we can easily accomplish this via 'drupal_add_js' and jquery by adding the below code into the 'description' field of the webform:

<?php

drupal_add_js

( '

$(function () { // make this code initialize when DOM loads
    $("#edit-submit").submit(function () { // optional: replace "#edit-submit" with whatever CSS selector you want (ex: form, ID or class)
        tracking("track_submit_quote"); // add custom function here
    });
});

;'

,'inline');

?>

'drupal_add_js' puts the code in 'head' and uses 'submit' instead of 'click' ...

we can use 'click' on specific links like so:

<?php
drupal_add_js
( '

$(function () {
    $("a[href=\'http://www.somesite.com/\']").click(function () {
        tracking("track_submit_site");
    });
});

;'

,'inline');

?>

Comments

what is the significance of

what is the significance of 'inline' in drupal_add_js ? What does it do?

It puts the code in instead

It puts the code in 'head' instead of including it in the global javascript file...

<script type="text/javascript" src="/sites/default/files/js/js_4952ecb022278d9734b57e31a63cc465.js"></script>

I'm not sure if there is any benefit to doing it this way, it just helps me easily see the code in source when I was debugging it.

it looks like this:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

$(function () {
$("#edit-submit").submit(function () {
tracking("track_submit_quote");
});
});

;
//--><!]]>
</script>

</head>

Can other tracking solution use this ?

Can other tracking solution use this

Post new comment

The content of this field is kept private and will not be shown publicly.