how to capture variables into the window.location.search when submitting a form?
Ok, so I have a form, and here's what I want to do with it:
Upon submitting, (provided submission is successful):
- Capture the value of a specific input field 'x' in the form into a variable 'xval'
- Append the value开发者_Go百科 of the variable 'xval' to the url
- And navigate to a specific page...
See, I have a few pages which are conditional in their content, depending on variables that I pass through the url... So the address on step 1 looks like this:
whatever.com/products.html?home?try
On step 2, which is the form, it looks like this"
whatever.com/products.html?home?try?5?john@gmail.com
Step 3, is supposed to read the url, and accordingly show information.
To reiterate, I don't know how to capture the variables and append them to the url when the user supposedly completes step 2...
I have tried a function on the submit button, that causes the navigation to trigger without submit validation... I tried the 'onsubmit' event handler on the form tag itself, and it didn't seem to work...
Ideas? Suggestions?
I'd say: stick to the accepted way of defining form fields in a GET string (?this=that&foo=bar
). This would be a way to load your page with new parameters:
var locationstr = location.href.split('?')[0], //URL without params
try = document.getElementById('try_inputfield').value,
email = document.getElementById('email_inputfield').value,
newLocation = [locationStr,
'?home=1',
'&try=',
try,
'&email=',
email].join(''); // glue new parameters
location.replace(newLocation); // replace location
if you want to read and use the properties as defined per location.search
this is a string extension to convert the querystring into an object:
String.prototype.q2obj = function(){
var qArr = this.split('&')
,qObj = {}
,i =-1;
while(++i<qArr.length) {
qfrag = qArr[i].split('=');
qObj[qfrag[0]] = qfrag[1];
}
return qObj;
};
//usage
var queryObj = location.search.substr(1).q2obj();
Make sure you set the name attribute on your input components. If your using a simple form submissions something like this should append the values to the url.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form>
<input id="txt-name" name="name"/>
<button type="submit">Submit</button>
</form>
</body>
</html>
精彩评论