Jack
Jack

Reputation: 6620

How to pass values of selected checkboxes to the javascript function?

I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.

<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

Upvotes: 2

Views: 16485

Answers (2)

Vishak
Vishak

Reputation: 31

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("~"); 

you will get the data as tilde separated. Hope this helps you.

Upvotes: 0

TooShyToAsk
TooShyToAsk

Reputation: 194

I think your approach is old fashioned. Here's a jQuery version.

NOTE: you are adding multiple id="pro" and this is just wrong remove it

First add id="form" to your form

Here you can find a fiddle. :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);
         }  
     });
  });
});

Upvotes: 6

Related Questions