簡體   English   中英

如何將選定復選框的值傳遞給javascript函數?

[英]How to pass values of selected checkboxes to the javascript function?

我需要將選定復選框的值傳遞給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

我認為您的方法是過時的。 這是jQuery版本。

注意:您要添加多個id =“ pro”,這是錯誤的刪除

首先將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);
         }  
     });
  });
});
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("~"); 

您將獲得以波浪號分隔的數據。 希望這對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM