Javascript和Java獲取各種form表單信息的簡單實例


大家都知道我們在提交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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM