Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a .js that populates 2 <div>'s with the longitude and latitude data and its working perfectly. But I want to take that data and populate a form with it so I can capture it to my database when they hit submit. I do not care if the form is hidden or visible I just need when the page loads and the script shows the data it also is automatically placed in a form. Any help is greatly appreciated. Thank you.

The js is called main.js found below from and the code to populate the data on the page is:

    <section>
<ul>
               <dl>
                       <dt>Latitude:</dt>
                       <dd id="latitude">Please...</dd>
               </dl>
               <dl>
                       <dt>Longitude:</dt>
                       <dd id="longitude">Wait...</dd>
               </dl>
               <dl>
                       <dt>Accuracy:</dt>
                       <dd id="accuracy">While...</dd>
               </dl>
               <dl>
                       <dt>Timestamp:</dt><dd id="timestamp">Calculating...</dd>
               </dl>
</ul>           
</section>



    <!--Now  and this is my issue I need the <dd id="latitude"> and <dd id="longitude"> some how in
a form to get in a SQL database -->




<ul class="pageitem">
                       <li class="smallfield"><span class="name">latitude</span><input
placeholder="" id="latitude" name="latitude" type="num" />
                       </li></ul>
<ul class="pageitem">
                       <li class="smallfield"><span class="name">Longitude</span><input
placeholder="" id="longitude" name="longitude" type="num" />
                       </li></ul>

The best documentation so far I have found is: How do I collect data from a div to use in a form

But I cannot get this working. Thank you all in advance.

The JavaScript I am using is:

/*
 * 
 * Find more about this app by visiting
 * http://miniapps.co.uk/
 *
 * Copyright (c) 2010 Alex Gibson, http://miniapps.co.uk/
 * Released under MIT license
 * http://miniapps.co.uk/license/
 * 
 */

var geoUtilityApp = (function() {

    var updateLocation = null;

    return {

        //initializes watchPosition.
        init: function () {

            updateLocation = navigator.geolocation.watchPosition(geoUtilityApp.success, geoUtilityApp.fail, {enableHighAccuracy: true});

        },

        success: function (position) {

            var timeStamp = null,
            heading = null,
            accuracy = null,
            altAccuracy = null,
            speed = null;


            //we must check to see whether or not each piece of data has been returned in the success call.
            //if a piece of data has been returned, we then update the meter readout.

            if(!position.coords.latitude) {
                document.querySelector('#latitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#latitude').innerHTML = position.coords.latitude;
            }

            if(!position.coords.longitude) {
                document.querySelector('#longitude').innerHTML = 'Calculating';
            }
            else {
                document.querySelector('#longitude').innerHTML = position.coords.longitude;
            }

            if(!position.coords.accuracy) {
                document.querySelector('#accuracy').innerHTML = 'Calculating';
            }
            else {
                accuracy = Math.round(position.coords.accuracy);
                document.querySelector('#accuracy').innerHTML = accuracy + ' meters';
            }

            if(!position.timestamp) {
                document.querySelector('#timestamp').innerHTML = 'Calculating';
            }
            else {
                //convert timestamp to be more human readable.
                timeStamp = geoUtilityApp.formatTimeStamp(position.timestamp);
                document.querySelector('#timestamp').innerHTML = timeStamp;
            }

            //update 'map' button href.
            geoUtilityApp.setMapURL(position.coords.latitude, position.coords.longitude);

            //update 'Mail location info' button href.
            geoUtilityApp.updateMail(position.coords.latitude, position.coords.longitude, accuracy, position.coords.altitude, altAccuracy, speed, heading, timeStamp);

        },

        //called if watchPosition returns an error.
        fail: function(error) {

            switch(error.code) {
                case 0:
                    // unknown error alert error message
                    alert('An unknown error occured');
                    break;

                case 1:
                    // permission denied alert error message
                    alert('Permission denied by user');
                    break;

                case 2:
                    // position unavailable error message
                    alert('Position unavailable');
                    break;

                case 3:
                    // timeout error message
                    alert('The request timed out');
                    break;
            }
        },


        //function that stops watchPosition, if we wished to call it
        stop: function() {

            navigator.geolocation.clearWatch(updateLocation);
        },

        //updates the href of the 'Map' button.
        setMapURL: function(latitude, longitude) {

            var URL = 'http://maps.google.com/maps?q=' + latitude + ',' + longitude;

            document.querySelector('#map').onclick = function() {
                window.open(URL);   
            };
        },

        //updates the href of the 'Mail location info' button.
        updateMail: function(latitude, longitude, accuracy, timeStamp) {

            (!latitude) ? latitude = '?' : latitude = latitude;
            (!longitude) ? longitude = '?' : longitude = longitude;
            (!accuracy) ? accuracy = '?\n' : accuracy += ' meters\n';
            (!timeStamp) ?timeStamp = '?\n\n' : timeStamp += '\n\n';

            var subject = 'My location';
            var body = 'Latitude: ' + latitude + '\nLongitude: ' + longitude + '\nAccuracy: ' + accuracy + 'Timestamp: ' + timeStamp + 'http://maps.google.com/maps?q=' + latitude + ',' + longitude + '\n';

            document.querySelector('#maillink').href = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
        },

        //toggles the large 'Mail location info' button.
        sendMail: function() {

            var mailLink = document.querySelector('#maillist');

            if (mailLink.style.display === 'none') {
                mailLink.style.display = 'block';
            }
            else {
                mailLink.style.display = 'none';
            }
        },

        //takes a variable that is degrees clockwise from true north and returns the relevant compass direction.


        //takes a Unix timestamp and returns a formatted, human readable timestamp.
        formatTimeStamp: function(timestamp) {

            var date = new Date(timestamp);

            var month = date.getUTCMonth() + 1,
            day = date.getUTCDate(),
            year = date.getUTCFullYear(),
            hours = date.getUTCHours() - 5,
            minutes = date.getUTCMinutes(),
            seconds = date.getUTCSeconds(),

            formattedTime =  year + '-' + month + '-' + day + ' T ' + hours + ':' + minutes + ':' + seconds;

            return formattedTime;
        },

        loaded : function() {

            //test to see if browser supports geo location api.
            if (window.navigator.geolocation) { 

                //hide the address bar if visible.
                window.scrollTo(0,0);

                //hack to enable active pseudo selectors on buttons in mobile webkit
                document.addEventListener("touchstart", function() {},false);

                //hide the mail list items button.
                document.querySelector('#maillist').style.display = 'none';

                //initialise the app.   
                geoUtilityApp.init();

                //add an event listener for when the mail button is clicked.
                document.querySelector('#mail').addEventListener('click', geoUtilityApp.sendMail, false);

            } else {  
                alert('Your browser does not support Geolocation API. Sorry!');
            }
        }
    };

}());

window.addEventListener("DOMContentLoaded", geoUtilityApp.loaded, true);
share|improve this question

2 Answers

up vote 0 down vote accepted

Place this form on your html code, wherever you want:

<form action="your_form_destination.php" method="post">
 <input type="hidden" id="long" name="long" />
 <input type="hidden" id="lat" name="lat" />
<input type="submit" value="Save values" />
</form>

And on your code, add this:

       //......
        if(!position.coords.latitude) {
            document.querySelector('#latitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#latitude').innerHTML = position.coords.latitude;
            document.getElementById("lat").value =  position.coords.latitude;
        }

        if(!position.coords.longitude) {
            document.querySelector('#longitude').innerHTML = 'Calculating';
        }
        else {
            document.querySelector('#longitude').innerHTML = position.coords.longitude;
            document.getElementById("long").value =  position.coords.longitude;
        }
      //......

That should take care of your problem, and when you click on the button, the information will be posted to your php script.

Let me know if it helps!

share|improve this answer
When you say "and on your code add this" where should I add this? I have tried a few places of the main.js with no luck – PaperBagged Oct 8 '11 at 4:11
Thank You! This solved my issues! – PaperBagged Oct 8 '11 at 5:11

Name your form inputs, then select them with your JS like so:

 <form action='#' method='post'>
 <input type='hidden' id='hidden1' name='hidden1' value=''/>
 <input type='text' id='text1' name='text1' value='text'/>
 </form>

 <script>
      //Add this code into whatever javascript you want to populate the form
      var thisElem = document.getElementById("hidden1");
      thisElem.value = yourOtherJavascriptValue;
 </script>

If you dont want the user to see this info just use multiple hidden elements, otherwise use texts

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.