简体   繁体   中英

Print JS Variable in Form

I´d like to pass a javascript variable to php and I thought of using a hidden input field in my form. Here is my code for that so far:

<input type="hidden" name="city" value="<script type='text/javascript'>document.write(geoip_city());</script>" />

Unfortunally this doesnt work as the output is exact the same as above instead of the cityname as value. Could any1 point me in the right direction? I am not sure where the problem is..

Thanks!

Hidden variable was good idea (if it is part of a form that gets submitted).

You can set it like this, provided that you add an id of city to this input.

<script type="text/javascript">
    document.getElementById('city').setAttribute('value', geoip_city());
</script>

You can put that script towards the bottom of the page, or with other javascript if you have some already. just make sure that input element exists at the time that it runs

<script>
   function davidIsPedantic(){
      document.getElementById('city').value = geoip_city();
   }
</script>

<input type="hidden" id="city" name="city" />

Edit: There you go. Call the davidIsPedantic() function when you want to update the input, so long as the element has loaded. To call it as soon as the page is loaded, use this:

window.onload = davidIsPedantic();

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