Search code examples
htmlform-fields

Carry form field values to next page in plain HTML using javascript


Unlike textbox, radio button and checkbox is it possible to carry values of textarea and select tag to another page in plain HTML using javascript? if yes then how?


Solution

  • There are two steps to read form values using HTML and Javascript.

    Use the GET method

    Modify your form to use the GET method instead of POST. POST data can only be read on the server side. You want to read the form data on the client side, so you must ensure that the data exists in the URL:

    <form method="get">
    

    When you submit your form, you will see your data in the URL, like

    http://localhost/yourTarget.html?field1=value&field2=value
    

    Read the GET data via Javascript

    The JavaScript to read the query parameters (everything after the '?') is quite simple:

    window.location.search;
    

    Using the example URL above, this code will return '?field1=value&field2=value'

    Here is a functional (though rudimentary) example:

    <form method="get">
        <textarea name="mytext">Text area value</textarea>
        <input type="submit" value="Submit" />
    </form>
    
    Input values:
    <div id="inputValues"></div>
    
    <input type="button" value="Get Input Values" id="retrieveInputValuesButton" />
    
    <script>
        var element = document.getElementById("retrieveInputValuesButton");
        element.onclick = function()
        {
            document.getElementById("inputValues").innerHTML = window.location.search;
        }
    </script>
    

    All that is left is to parse the query string to retrieve your values.