0

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.

4 Answers 4

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

What kind of problems can arise? I always refer my elements by its ID
Slapping IDs on everything can make it more likely that you'll eventually have duplicate IDs on a page (think includes, Ajax, etc.). While it's true that labels require IDs on their corresponding input elements to function properly, that really should be a fringe case. In my opinion, there's no reason to put an ID on a hidden form field when you can access it just as well with the forms collection.
1

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!

Comments

0

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

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.