2014-04-10 200 views
2

我需要將所選複選框的值傳遞給javascript方法,但它不檢測複選框。如何將選定複選框的值傳遞給javascript函數?

<form name="cat" method="POST" action="myaction">  
    <c:forEach items="${items}" var="item"> 
     <input type="checkbox" id="pro" name="pro" value="${item.id}"/> 
    </c:forEach> 
    ... 
    <input type="button" value="getItem" onclick="getItem(this.form)"/> 
</form> 

的Javascript

function getItem(frm) { 

    alert("size:" + frm.pro.length); <<< it returns size:unidentified 
    var values = ""; 
    for (var i = 0; i < frm.pro.length; i++) 
    { 

     if (frm.pro[i].checked) 
     { 

       values = frm.pro[i].value + ","; 

     } 
    } 
    alert(values); << it is empty 
    .... 
    //pass values to the back-end 

回答

5

我覺得你的做法是老式的。這是一個jQuery版本。

注意:您要添加多個ID =「親」,這是錯誤的刪除

首先添加id="form"到窗體

在這裏你可以找到一個小提琴。 :d

http://jsfiddle.net/SXffG/3/

HTML:

<form id="form" name="cat" method="POST" action="myaction">  
     <input type="checkbox" name="pro" value="1"/> 
      <input type="checkbox" name="pro" value="2"/> 
      <input type="checkbox" name="pro" value="3"/> 
      <input type="checkbox" name="pro" value="4"/> 
      <input type="checkbox" name="pro" value="5"/> 
      <input type="checkbox" name="pro" value="6"/> 
    <input type="button" class="getItem" value="getItem"/> 
</form> 
<div id="info">Click the button</div> 

的JavaScript

var allVals = []; 
$(function() { 
    $('#form .getItem').click(function() { 
     allVals = [] 
    $('#form :checked').each(function() { 
     allVals.push($(this).val()); 
    }); 
    //alert("Values " + allVals); 
    $.ajax({ 
     type: "POST", 
     url: "http://localhost:8080/example/ajaxSubmit.action", 
     data: "allVals=" + allVals, 
     success: function(response){ 
      $('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response); 
     }, 
     error: function(e){ 
      $('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e); 
     } 
    }); 
    }); 
}); 
+1

問題是,函數應該接收數據並在用戶單擊指定的按鈕後將它們發送到後端。如何讓你的代碼做到這一點? – Jack

+0

好的,能滿足你的需求嗎?我編輯小提琴和答覆添加ajax請求,當你點擊按鈕數據將被髮送到'url'。 :d – TooShyToAsk

0
var check = document.getElementsByName("pro"); 
var textArray = [];        
    for(var c = 0; c < check.length;c++){ 
     if(check[c].checked){ 
     textArray .push(check[c].value);         
     } 
    } 
    textArray = textArray .join("~"); 

你將得到的數據作爲波浪分離。希望這可以幫助你。

相關問題