0

Let's say I have this piece of code from first.html

<input type="text" id="name">
<a href="second.html">Go to next page</a>

How can I make it that when you go to second.html, javascript alerts the value of [name] from first.html OR the html adds an h1 tag with the value of [name] from first.html

2 Answers2

0

you could use onclick function on anchor tag.

<input type="text" id="name">
<a onclick="goToNextPage()">Go to next page</a>
<script>
function goToNextPage()
{
var value = document.getElementById('name').value;
 window.location.href="second.html?name="+value;
}
</script>

Or you could use form.submit() to post the form values to request.

As HTML is only markup language, not programming language. So, you would need either php/ javascript to fetch that value on second page.

function qs(search_for) {
        var query = window.location.search.substring(1);
        var parms = query.split('&');
        for (var i=0; i<parms.length; i++) {
            var pos = parms[i].indexOf('=');
            if (pos > 0  && search_for == parms[i].substring(0,pos)) {
                return parms[i].substring(pos+1);;
            }
        }
        return "";
    }

and then call that function in your second page as.

    <script type="text/javascript">
  document.write(qs("name"));
</script>
Rohit Batta
  • 482
  • 4
  • 16
0

You can use document.getElementById() function to get input and access it's value property to read what was entered there.

The onclick attribute on your anchor element will execute a custom function which will take the href property of the anchor and append the url-encoded value of the input field.

Then it will go to that new URL.

The return false ensures that built-in href event does not execute.

function link(anchor) {
  var name = document.getElementById("name").value
  var url = anchor.href + "?name=" + encodeURIComponent(name);
  window.location.href = url;
}
<input type="text" id="name">
<a href="second.html" onclick="link(this); return false;">Go to next page</a>

To read the passed in variable on the receiving page, use the technique described in this SO post:

How can I get query string values in JavaScript?

Community
  • 1
  • 1
martynasma
  • 8,542
  • 2
  • 28
  • 45
  • thanks, but when i want to alert it in second.html, the javascript alert box is empty –  Aug 04 '15 at 17:04
  • You can use the technique described in this SO article to read passed in query string variables: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – martynasma Aug 04 '15 at 17:14