简体   繁体   English

将Javascript“ document.write”值传递给隐藏表单提交值

[英]Pass Javascript “document.write” values to hidden form submit value

I have a script that sets document.write values to a webpage that works fine, what I am trying to do is set the document.write values "also" to a hidden html field for submission form. 我有一个脚本,可以将document.write值设置为可以正常工作的网页,我想做的是将document.write值“也”设置为用于提交表单的hidden html字段。

Here is what i have tried and cannot seem to get it to work: 这是我尝试过的方法,似乎无法使其正常工作:

<script language="JavaScript" type="text/javascript" src="http://www.geoplugin.net/javascript.gp"></script>

 <script language="javascript">
  document.forms('SendPasswordForm').GeoCity.value=geoplugin_city();
 </script>

<form id="SendPasswordForm" action="#" method="POST">

 <input type="hidden" name="GeoCity" value="">

</form>

<script language="Javascript">document.write(" "+geoplugin_city()+", "+geoplugin_region()+", "+geoplugin_countryCode()); </script>

You can move the second script tag below form tag as the script to update GeoCity field cannot find the field as it was declared afterwards. 您可以将第二个脚本标签移到form标签下,因为用于更新GeoCity字段的脚本找不到此字段,因为此字段后来被声明。

You can find the updated code below: 您可以在下面找到更新的代码:

<script language="JavaScript" type="text/javascript" src="http://www.geoplugin.net/javascript.gp"></script>

<form id="SendPasswordForm" action="#" method="POST">
    <input type="text" id="GeoCity" name="GeoCity" value="">
</form>

<script language="javascript">
    document.forms['SendPasswordForm'].GeoCity.value = geoplugin_city();
</script>

<script language="Javascript">
    document.write(" " + geoplugin_city() + ", " + geoplugin_region() + ", " + geoplugin_countryCode());
</script>

You should use jQuery for this. 您应该为此使用jQuery。 jQuery significantly simplifies operations like this where plain JavaScript can be troublesome. jQuery大大简化了这样的操作,而纯JavaScript可能会麻烦。 jQuery takes just a few minutes to add to your project. jQuery仅需几分钟即可添加到您的项目中。

It can be downloaded by right-clicking Download the compressed, production jQuery 3.2.1 -> Save As ... from this link: http://jquery.com/download/ 可以通过右键单击下载压缩的生产版jQuery 3.2.1- >另存为...来从以下链接下载: http : //jquery.com/download/

Then simply include it in your html- file: 然后只需将其包含在您的html-文件中:

<script language="JavaScript" type="text/javascript" src="jquery.js"/>

With jQuery included, all you need to do to change the value of your hidden field is: 使用jQuery,更改隐藏字段的值所需要做的就是:

  1. Give your item an ID such as: 给您的商品一个ID,例如:

     <input id="HiddenInputID" type="hidden" name="GeoCity" value=""> 
  2. Then change the value like this: 然后像这样更改值:

     $('#HiddenInputID').val('My new value'); 

I have made this working example- code: https://jsfiddle.net/09uwg5zq/ 我已经制作了这个工作示例代码: https : //jsfiddle.net/09uwg5zq/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM