简体   繁体   中英

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.

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.

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 significantly simplifies operations like this where plain JavaScript can be troublesome. jQuery takes just a few minutes to add to your project.

It can be downloaded by right-clicking Download the compressed, production jQuery 3.2.1 -> Save As ... from this link: http://jquery.com/download/

Then simply include it in your html- file:

<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:

  1. Give your item an ID such as:

     <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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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