0

So i have a form and as part of it you must enter in a date and a time with a datetime input, like so..

<form action="confirmForm.html">
 <p>What date and time suits you? </p>
 <input id="datetime" type="datetime-local" />
</form>

and then on the next page, there's just a span tag.

<body onload="formConfirm();">
 <span id="confirm"></span>
</body>

And my JavaScript..

var test = document.getElementById('datetime').value;
document.getElementById("confirm").innerHTML = test;

I expected it to print the datetime to the span tag, but it does nothing. Tried it with alert(test); too but got nothing there either. Pretty confused about this.

Edit: oh and the form has a submit button and all that, forgot to include it here.

David Lawlor
  • 53
  • 1
  • 1
  • 4

1 Answers1

0

In order to access the form values on the next page you need to pass them using a get or post method. Use the method attribute on the <form> element to tell it which one to use.

Normally you'd use post to send the form data to be processed on the server (using PHP or another server-side language). That being said, this question may be useful for using post with JavaScript.


Edit:
According to this answer you can't access post variables in JS on the client side, which makes sense.

But here it is with get:
(using this solution to parse the URI)

confirmForm.html

<body onload="formConfirm()">
    <span id="confirm"></span>
    <script>
        function formConfirm() {
            var dt = getParameterByName('datetime');
            alert(dt);
            document.querySelector('#confirm').innerHTML = dt;
        }

        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    </script>
</body>

Something important on the form page:
Make sure you give all fields a name attribute.

<form action="confirmForm.html" method="get">
    <p>What date and time suits you? </p>
    <input id="datetime" type="datetime-local" name='datetime'/>
    <button type="submit">Submit</button>
</form>
Community
  • 1
  • 1
Nelu
  • 16,644
  • 10
  • 80
  • 88