How to use HTML forms without a server
I am not a web-developer and want to understand the better way to pass variables. In the past I have used various ways to pass things to java script functions. I have never used forms as I always associated them with server and databases. I have a website in which user selections change the contents of the website.
I am wondering if you can use forms without any server just as a way to pass a few things to a javascript function where they are used to change the page content. For basic example, if someone selects male the page background becomes blue, if they choose female the background becomes pink. Would forms be th开发者_JAVA技巧e way to go and just onsubmit call a javascript function? How would I actually pass the form contents to the javascript function?
Yes you absolutely can use forms/inputs/any kind of html element and never talk to a server, just don't expect to store that data! You're right about using events (like the onsubmit one you mentioned) to trigger Javascript functions.
Here is a quick and dirty example (heavy on the dirty) that does sorta kinda what you'd like. Note that instead of waiting for the form to be submitted before the color change, I go ahead and do it immediately after they choose a gender from the dropdown.
http://jsfiddle.net/wG8K4/1/
You wouldn't pass the parameters. You could have "onsubmit" call a javascript function, and then within the function use javascript to access the actual controls that the user has selected. You could use the GetElementById function to retrieve a certain element, and then determine the value of that element.
If all you wanted to do was change the background color, you could use javascript to change the backgroundColor property of the body tag or any tag on the page.
You'd have to remember to return false from your function, though -- otherwise, the form would be submitted.
You don't need servers / databases to use forms. Forms are simply a method from passing variables from one file to another, regardless if that is an html file or some php script or what have you. If you stick to using GET forms, your form will naturally pack its data into the URL of your page at which time you can access them. For instance (borrowed from http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/):
<script language="javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
var usersName = $_GET('username');
if(typeof(usersName)!='undefined'){
document.write('<h1>Hi there, '+usersName+'</h1>');
}
</script>
<form>
<input type="text" name="username" />
<input type="submit" value="Say my name" />
</form>
The basic event you're going to look for is the form's submit
event. If you're okay with just using event handlers, you can just do something like this:
var myForm = document.getElementById('myForm');
myForm.onsubmit = function () {
// ...
};
Because you're just using JavaScript, you don't want the form to actually submit. (Side point: Because you're using JS, you should just build this form and add it to the page with JS, but that's a completely different issue.) You can cancel the form's default action like so:
myForm.onsubmit = function () {
// ...
return false;
};
Before we get into accessing data, make sure that you grab the elements you're going to need. It makes things a little faster, because you don't have to select the entire element from the DOM every time the form is submitted. For example:
var myForm = document.getElementById('myForm'),
myTextField = document.getElementById('myTextField'),
mySelectBox = document.getElementById('mySelectBox'),
// ...
Depending on what kind of form elements you have, there are different ways to access their data. Text inputs, text areas, and select boxes are really easy:
var textValue = myTextField.value,
selectValue = mySelectBox.value;
Radio buttons and check boxes are a little more complicated, because you have to go through every single one and see which one(s) is/are checked and which one(s) isn't/aren't, like so:
var isOneChecked = checkboxOne.checked,
isTwoChecked = checkboxTwo.checked;
Going with your example of blue/pink background, you would probably want something similar to this:
var myForm = document.getElementById('myForm'),
maleBox = document.getElementById('maleBox');
myForm.onsubmit = function () {
var isMale = maleBox.checked;
if (isMale) {
document.body.style.backgroundColor = 'manlyBlue';
} else {
document.body.style.backgroundColor = 'sexistPink';
}
};
Notes
If you do decide to go with event handlers, keep in mind that only one can be applied to your form at a time. If you want to attach a different function to the submit
event as well, you'll have to go with event listeners, which is a completely different ball game and introduces problems of its own.
The final example only checks the value of the "I'm a guy" element, because (presumably) you're using radio buttons and you only have two options. If "I'm a guy" is not checked, then the other one should be. But if the form starts out with neither option checked, then that could be considered a bug.
The final example also uses inline styles to change the body's background color. It hurt me to type. A much more bearable method would be to add/remove classes as needed, but again, that's kind of beyond the scope of this question.
Form elements can be used as a form of global variables - holding state that can be used and shared by all the javascript in a single page.
However, this could result in brittle and difficult to understand code.
I suggest keeping with passing parameters to functions, so long as you are in the context of a single page.
If you need to pass data to another page, then forms can make life easier - using a GET
form, the values on the form will be passed to the page referenced in the form action
attribute as key-value pairs. If you use the POST
method they will be transferred in the headers.
If your desire is to iterate through form elements using Javascript you can easily do this using the DOM since the form will have a length
property and each input
will be represented as an index of this array-like object:
So for:
<form id="f" action="">
Male<input type="radio" name="gender" value="male" />
Female<input type="radio" name="gender" value="female" />
<input type="submit" value="submit" />
</form>
You could do something like this:
var f = document.getElementById('f');
f.onsubmit = function (e) {
e = e || window.event;
var et = e.target || e.srcElement,
gender;
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
for (var i = 0, il = et.length; i < il; i++) {
if (et[i].name = 'gender' && et[i].checked) {
gender = et[i].value;
}
}
if (gender == 'male') {
document.body.style.backgroundColor = 'cyan';
} else if (gender) {
document.body.style.backgroundColor = 'pink';
}
};
See example →
精彩评论