Search code examples
javascriptdrupaldrupal-webform

Drupal: How to add JavaScript value to hidden form component


I want to get the user screen size as one of my hidden fields.

In pure HTML, I can get the input value as JavaScript, e.g.:

document.write(screen.width + " x " + screen.height)

If I set[input format] of the page to [full html] or [php code], if I set the component value to -

<script>document.write(screen.width + " x " + screen.height);</script>

the SCRIPT tags are omitted, and the quote signs becomes " . It seems that the [value] field is transformed to safe HTML entities.

Is there a way to add a hidden form component with JavaScript value, in Drupal webforms?

EDIT: Solved:

1 - Copy the original
...sites/all/modules/webform/webform-form.tpl.php 
to
...sites/all/themes/myTheme/webform-form-myFormNodeId.tpl.php 


2 - Add the following lines to webform-form-myFormNodeId.tpl.php

  echo "<script>";
  echo "document.getElementById('edit-submitted-userscreen').value = screen.width + 'x' + screen.height;";
  echo "</script>";


3 - admin/settings/performance : [Clear cached data]

Edit: I can add some PHP values as

%server[HTTP_USER_AGENT]

How do I add JavaScript values?

Edit 2: I tried changing the node [input format] to [php code] and the following [form component][value], but all of them did not work:

1 - drupal_add_js(screen.width + " x " + screen.height);
2 - <script>document.write(screen.width + " x " + screen.height);</script>
3 - <?php echo "<script language=\"javascript\">" . "document.write (screen.width + ' x ' + screen.height);" . "</script>"; ?>

4 - full html + 
<script>
jQuery('#edit-submitted-userscreen').val(screen.width + 'x' + screen.height);
</script>
=> in View Page Source, I see:
<input type="hidden" name="submitted[userscreen]" id="edit-submitted-userscreen" value="
jQuery(&#039;#edit-submitted-userscreen&#039;).val(screen.width + &#039;x&#039; + screen.height);


"  />

[SCRIPT tags are replaced with NewLineChar ???]

=> so when I fill in the form, I receive email with the original string:

userScreen: jQuery('#edit-submitted-userscreen').val(screen.width + 'x' + screen.height);

Solution

  • It's as simple as:

    1) Define a hidden field in your form.

    $form['resolution'] = array(
      '#type' => 'hidden'
    );
    

    2) Apply value with jQuery to your field.

    $('#edit-resolution').val(screen.width + " x " + screen.height);
    

    EDITED

    Try to provide this value to your textarea with Full HTML mode enabled.

    <input type="hidden" name="submitted[userscreen]" id="edit-submitted-userscreen" value="" />
    
    <script>
    jQuery('#edit-submitted-userscreen').val(screen.width + 'x' + screen.height);
    </script>
    

    SECOND EDIT

    <input type="hidden" name="submitted[userscreen]" id="edit-submitted-userscreen" value="" />
    <script>document.getElementById('edit-submitted-userscreen').value = screen.width + 'x' + screen.height;</script>