-2

I have to get all the selected checkboxes value in a JavaScript without any button action in the form and display in my jsp page.

This is my code where I am getting the value from database.

<span><li class="list-group-item">
<input type="checkbox" value="${subFill.fillingname}"  name="fillings"> ${subFill.fillingname}</input>
</li></span>

I have to select multiple checkbox and get those name.

1 Answers1

0

Here namesArray will hold the values off all the checkboxes which were checked.

You can loop through this array and display the values on JSP page. Sorry, I'm not much exprienced with JSP but guess that is possible. The js code is,

var namesArray = [];
var checkBoxes = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < checkBoxes.length; i++) {
    checkBoxes[i].addEventListener('change', function() {
        if(this.checked){
            console.log(this.value);
namesArray.push(this.value);
console.log(namesArray);
                }
    });
}

EDIT:- For addition of values to a div and saving the values in session

To add the values to a div use,

  var namesArray = [];
    var div = document.getElementById('divID'); //mention your div's id
        var checkBoxes = document.querySelectorAll('input[type=checkbox]');
        for(var i = 0; i < checkBoxes.length; i++) {
            checkBoxes[i].addEventListener('change', function() {
                if(this.checked){
                    console.log(this.value);
                    div.innerHTML = div.innerHTML + this.value + ' ';
                    namesArray.push(this.value);
                    console.log(namesArray);
                        }
            });
        }

Then to send these values to the server, use ajax on form submit, send the namesArray as the data. Have a look at these, example1, example2, example3 etc. To save these values in a session, write some logic in the servlet. Store a key-value pair in the Session, key being a String or something, and value being an Array of Strings, i.e., in this case the values of checkboxes. So you can get the array by doing Session.get('your key'). Hope this helps.

Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30