Drupal:如何将JavaScript值添加到隐藏的表单组件

时间:2012-02-15 10:51:33

标签: javascript drupal drupal-webform

我希望将用户屏幕尺寸作为隐藏字段之一。

在纯HTML中,我可以将输入值作为JavaScript,例如:

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

如果我将页面的[输入格式]设置为[full html]或[php code],如果我将组件值设置为 -

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

省略了SCRIPT标签,引号变为“。似乎[value]字段转换为安全的HTML实体。

有没有办法在Drupal webforms中添加带有JavaScript值的隐藏表单组件?

编辑:解决:

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]

编辑: 我可以添加一些PHP值

%server[HTTP_USER_AGENT]

如何添加JavaScript值?

编辑2: 我尝试将节点[输入格式]更改为[php code] 和以下[表单组件] [值],但所有这些都不起作用:

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标签被NewLineChar替换???]

=&GT;因此,当我填写表格时,我会收到带有原始字符串的电子邮件:

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

1 个答案:

答案 0 :(得分:2)

这很简单:

1)在表单中定义隐藏字段。

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

2)将jQuery应用于你的领域。

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

<强> EDITED

尝试在启用了Full HTML模式的情况下为您的textarea提供此值。

<input type="hidden" name="submitted[userscreen]" id="edit-submitted-userscreen" value="" />

<script>
jQuery('#edit-submitted-userscreen').val(screen.width + 'x' + screen.height);
</script>

第二次编辑

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