2

I am working in spring mvc, I used the following line to generate the checkboxes from DB table.

<td><input type="checkbox" name="loanId" value="${loan.id}" class="it"></td>

I need to get the index of this selected values in my java controller. I am able to get the values which are selected, but how to get the index values? enter image description here following code is I am using

        String[] loanIds = request.getParameterValues("loanId");

        for (String string : loanIds) {
            System.out.println("loanIds****"+string);
        }           
DevGo
  • 1,045
  • 1
  • 16
  • 42

3 Answers3

1

You need javascript to get the index of checkbox and set it to hidden field :

var ids = document.getElementsByName('loanId');
var ind = document.getElementById('loanIndex');
var put = function() {
  var arr = [];
  var i = -1;
  while (ids[++i])
    if (ids[i].checked) arr.push(i);
  ind.value = arr.join(',');
  alert('selected index: ' + ind.value);
};
var i = -1;
while (ids[++i])
  ids[i].onchange = put;
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="hidden" name="loanIndex" id="loanIndex" value="" />

In controller:

String[] loanIndex= request.getParameter("loanIndex").split(",");
  • This is my exact question http://stackoverflow.com/questions/29347815/checkbox-and-respective-rows-values-from-jsp-to-java-controller-file – DevGo Mar 31 '15 at 06:28
0

There is no direct method for this purpose.

You can have index as value which is passed on selecting checkbox. You can use this index-value later to get selected record data from in-memory collection i.e. when user selects checkbox and submits request, on server side you will fetch ParameterValues from request and list data from datasource, compare ids then derive selected list.

Pranalee
  • 3,389
  • 3
  • 22
  • 36
  • This is my exact question http://stackoverflow.com/questions/29347815/checkbox-and-respective-rows-values-from-jsp-to-java-controller-file – DevGo Mar 31 '15 at 06:27
0

Using Jquery

var indexString;

var index;

$('#.it').each(function () {



    $(this).find('.SomeCheckboxClass').each(function () {
        if ($(this).attr('checked')) {
            index = $(this).index();
            indexString = index + ",";
        }
    });

    });

post this indexString, it is a comma separated index string.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • This is my exact question http://stackoverflow.com/questions/29347815/checkbox-and-respective-rows-values-from-jsp-to-java-controller-file – DevGo Mar 31 '15 at 06:27
  • @Mary.Hansen play with Jquery/Javascript, above is the correct approach. – Ankur Singhal Mar 31 '15 at 06:29
  • I just copied this code and pasted in my jsp under script. I cant see any console while clicking on checkboxes. I just put console.log("Hello"); in function. – DevGo Apr 01 '15 at 05:43