大家都知道我们在提交form的时候用了多种input表单。可是不是每一种input表单都是很简单的用Document.getElementById的方式就可以获取到的。有一些组合的form类似于checkbox或者radio或者select我们如何用javascript获取和在服务器中获取提交过来的参数呢?多说无用、上代码:
Jsp-html代码:
<form action="input.do" name="formkk">
<table>
<tbody>
<tr>
<td>text:</td>
<td>
<input type="text" name="text">
</td>
</tr>
<tr>
<td>password:</td>
<td>
<input type="password" name="pass">
</td>
</tr>
<tr>
<td>radio:</td>
<td>
<input type="radio" name="xingbie" value="1">
男
<input type="radio" name="xingbie" value="2">
女
</td>
</tr>
<tr>
<td>checkbox:</td>
<td>
足球:<input type="checkbox" name="hobby" value="1" />
篮球:<input type="checkbox" name="hobby" value="2" />
拍球:<input type="checkbox" name="hobby" value="3" />
斗球:<input type="checkbox" name="hobby" value="4" />
</td>
</tr>
<tr>
<td>hidden:</td>
<td>
<input type="hidden" value="123" name="hidden"/>
</td>
</tr>
<tr>
<td>option:</td>
<td>
<select name="opt" id="opt">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</td>
</tbody>
</table>
<input type="button" value="提交" onclick="javascript:check()"/>
</form>
Javascript:
function check(){
var radio = document.getElementsByName("xingbie");
var checkbox = document.getElementsByName("hobby");
var select = document.getElementById("opt");
//获取select标签
var index = select.selectedIndex;
var text = select.options[index].text;
var value = select.options[index].value;
//获取radio标签
for(var i=0;i<xingbie.length;i++){
if(xingbie.item(i).checked){
var val = xingbie.item(i).getAttribute("value");
break;
}
continue;
}
//获取checkbox标签
for(var i=0;i<hobbys.length;i++){
if(hobbys[i].checked){
alert(hobbys[i].value);
}
continue;
}
//提交form表单
document.formkk.submit();
}
Java:
String[] hobbys = request.getParameterValues("hobby"); //checkbox
String text = request.getParameter("text"); //text
String password = request.getParameter("password"); //password
String xingbie = request.getParameter("xingbie"); //radio
request.getParameter("hidden");
request.getParameter("opt"); //select