Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  47] [ 7]  / answers: 1 / hits: 16547  / 8 Years ago, fri, june 10, 2016, 12:00:00

I need to the add a JavaScript variable to a link in action form. 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, as follows:


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

More From » url

 Answers
6

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>

[#61815] Wednesday, June 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kayap

Total Points: 634
Total Questions: 83
Total Answers: 110

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;