简体   繁体   中英

How do I pass a variable from JavaScript (Google Maps API) to my Form Input

There maybe some simlar questions to this but I can't see anything that really solves my problem. I would like to pass the contents of a variable in JavaScript either into a PHP variable or a html form value.

Cheers, knowing how to do both would be very helpful.

To save a Javascript variable into a html form element, I would go using DOM:

  //your target html form element must have a unique ID
  var input_element = document.getElementById('unique_id');
  input_element.value = google_maps_api_variable;

That's it!

Littering your document with IDs can cause problems down the line. You should use IDs only when you really need to.

Why not do it with the DOM Level 0 forms collection?

<form name="myForm">
    <input name="myInput" type="hidden" />
</form>

<script type="text/javascript">
    var foo = 42;
    document.forms["myForm"].elements["myInput"].value = foo;
</script>

You could use ajax, get/post request to the php script so that php can save the value although I haven't worked with Google Maps API. This answer should help you on DevShed

You could use hidden fields in your form.

<input type="hidden" id="testField" />

Populate the value of your hidden field with the value of your variable, and it should be there when you submit it:

var variableWithData = 42; //get this from somewhere...
document.getElementById('testField').value = variableWithData;

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