简体   繁体   中英

Need Value generated from Javascript inserted into hidden form field

I am using a geo location script that generates the users city based on IP.

Header Code:

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>

Code that generates the city:

 <script language="JavaScript">document.write(geoip_city());</script>

My form looks like this:

<form name="form1" id="form1" method="post" action="script.php">Email: <input       size="35" type="text" name="email"> 
<input type="hidden" id="city" name="city" value="" >
    </form>

I need to be able to insert the value generated from the javascript into the value field of the form.

I cant seem to do it, ive tried various ways like placing this after the form:

<script type="text/javascript"> 
document.getElementById("city").value = "1";
alert(document.getElementById("city").value);
</script>

This is on a page that has been saved as .php.

You're just inserting "1". Try:

 <script language="JavaScript">
 var city = geoip_city();
document.write(city);
</script>

and

<script type="text/javascript"> 
document.getElementById("city").value = city;
alert(document.getElementById("city").value);
</script>

This may need refinement - I haven't used this library. The variable city allpws you to read the location twice.

That company seems to no longer support that version of the js library . Here's how you'd do it using their latest lib

 "use strict"; var getCity = function( geoipResponse ){ var cityName = geoipResponse.city.names.en || 'your city'; document.getElementById('city').value = cityName; alert(cityName); }; var fail = function(err) { alert(err.error); console.error(err); } geoip2.city( getCity, fail ); 
 <script src="http://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script> <form name="form1" id="form1" method="post" action="script.php"> Email: <input size="35" type="text" name="email" /> City: <input type="not_hidden" id="city" name="city" value="" /> </form> 

You can change the statement as

document.form1.city.value="new value";

this would work

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