Lanshore Lanshore - 5 months ago 7
Javascript Question

How to add JavaScript variables to form action

I need to the add a javascript variable to a link in action form. My question, is that possible?

JavaScript Function:

<script>
function parameter()
{
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
var vpid = getUrlVars()["pid"];
}
//var link = "second_02.html" + pid.toString();
</script>


and in my form I need to add the variable 'link' to a form action, like follows:

<form action='second_02.html + ?pid=vpid&' id="sky-form" class="sky-form">


I don't really know if I did explain well myself with the issue I am having.
Thanks in advance.

Answer

You'll need to do that programmatically via JavaScript.

After this line...

var vpid = getUrlVars()["pid"];

Add this one...

document.getElementById('sky-form').action = 'second_02.html?pid=' + vpid;

Given the nature of the content of vpid, then you could implements this in the load event of your window.

ALTERNATE METHOD 1

Here's an alternate method of doing what you appear to require, but it requires you to set the new location with the calculated parameter. You can amend the lines that try to get the text from the textbox, with whatever you need to append to your URL.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            function validateForm() {
                //alert('Validating form...');
                var text = document.getElementById('txtValue').value;
                text = escape(text);
                location.href = 'test.html?param=' + text;
                return false;
            }
        </script>
    </head>
    <body>
        <form id="frmTest" method="get" action="" onsubmit="return validateForm();">
            <input id="txtValue" type="text" value="foobar">
            <input id="btnSubmit" type="submit" value="Submit">
        </form>
    </body>
</html>

ALTERNATE METHOD 2

This method allows you to continue to use your form, even with its GET method, but you set the value of a hidden field, that will then be appended to the URL in the querystring during submission.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            function validateForm() {
                //alert('Validating form...');
                document.getElementById('hidTest').value = 'some calculated value';
                return true;
            }
        </script>
    </head>
    <body>
        <form id="frmTest" method="get" action="" onsubmit="return validateForm();">
            <input id="txtValue" type="text" value="foobar">
            <input id="btnSubmit" type="submit" value="Submit">
            <input name="hidTest" id="hidTest" type="hidden" value="testIt">
        </form>
    </body>
</html>
Comments