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);
        }           
3
  • You need javascript to get the index of checkbox and set it to hidden field Commented Mar 31, 2015 at 6:06
  • @Mary.Hansen Are you using Jquery/Javascript Commented Mar 31, 2015 at 6:07
  • I am using just javascript only Commented Mar 31, 2015 at 6:08

3 Answers 3

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(",");
Sign up to request clarification or add additional context in comments.

1 Comment

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.

1 Comment

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.

3 Comments

@Mary.Hansen play with Jquery/Javascript, above is the correct approach.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.