如果你只是使用文本字段在Javascript中你并不真的需要一个method
或action
属性
添加submit
按钮和onsubmit
处理程序,以这样的形式,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
然后,在JavaScript你可以有这个processForm
功能
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
注意如何在OP的示例中的控件没有一个ID,虽然... –
确实。 OP将不得不为他/她的输入控件添加一个ID。 – Lowkase
我的观点是:不一定。使用名称就好了,因为表单元素无论如何都需要一个名字(至少当他们还通过表单与服务器进行通信时),为什么不使用它呢? –