大家都知道我們在提交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
以上就是小編為大家帶來的表單元素值獲取方式js及java方式的簡單實例全部內容了,希望大家多多支持~