表单提交时不会覆盖默认值
我在表单内有一个隐藏字段,我使用 Drupal 的表单 API 创建该字段,如下所示:
$form['position'] = array(
'#type' => 'hidden',
'#default_value' => '57.149953,-2.104053',
'#attributes' => array(
'id' => 'geoposition',
)
);
当我加载呈现表单的页面时,我有一些 JavaScript 可以像这样编辑隐藏字段:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, noPosition, 10);
}
function getPosition(position) {
var pos = document.getElementsByName("position");
pos.value = position.coords.latitude + "," + position.coords.longitude;
alert(pos.value);
}
现在,该片段中的最后一条语句实际上输出了用户当前位置的正确值。但是,当我提交表单时,传递到服务器进行操作的值是默认值,而不是更新后的值。提交表单后使用的值如下所示:
$map_field .= 'src="http://maps.google.co.uk/maps?q='.$form_state['values']['position'].'&output=embed"></iframe>';
有什么想法吗?
谢谢,
I've got a hidden field inside a form, which I create using Drupal's form API like this:
$form['position'] = array(
'#type' => 'hidden',
'#default_value' => '57.149953,-2.104053',
'#attributes' => array(
'id' => 'geoposition',
)
);
When I load the page in which the form is rendered, I have a little bit of JavaScript that edits the hidden field like so:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, noPosition, 10);
}
function getPosition(position) {
var pos = document.getElementsByName("position");
pos.value = position.coords.latitude + "," + position.coords.longitude;
alert(pos.value);
}
Now, the last statement in this snippet actually outputs the correct value of the user's current position. However, when I submit the form, the value passed onto the server for manipulation is the default value, and not the updated value. The value to use after the form has been submitted is picked up like this:
$map_field .= 'src="http://maps.google.co.uk/maps?q='.$form_state['values']['position'].'&output=embed"></iframe>';
Any ideas?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是我要做的:
1)暂时禁用 js。
2)使用xdebug查看表单提交前后的值。这应该有助于查看是否出了问题。
干杯,
维沙尔
This is what I wud do:
1) Disable to js for now.
2) Use xdebug to see the value before and after the form has been submitted. This should help to see if something is going wrong.
Cheers,
vishal
考虑使用 #value,而不是使用 #default_value - 因为这是发布的值。
Rather than using #default_value, consider using #value - because that is the value that gets posted.
最终通过使用 getElementById() 方法而不是 getElementsByName() 方法解决了这个问题。由于某种原因,这个名字不起作用。感谢大家的帮助。
Eventually solved it by using the getElementById() method instead of getElementsByName() method. For some reason the name wasn't working. Thanks all for your help.