Getting a list of selected checkboxes in a table
This is what I have in the table:
<td><g:checkBox name="book_${bookInstance.id}"/> </td>
And this is how I am trying to get the selected instances:
params.each{
if(it.key.startsWith("book_"))
books << (it.key - "book_") as Integer
}
I am getting an empty list. How to fix it? I am open to suggestions if you have a better solution.
+3
source to share
2 answers
Try to create a list of checkboxes with the same input name but different values.
<g:each in="${books}" var="bookInstance">
<g:checkBox name="books" value="${bookInstance.id}"/>
</g:each>
Then in your controller, you can get a list of the selected book ids with:
params.list('books')
+5
source to share
My answer was definitely late as the question was asked a while ago. Anyway, I solved a similar problem, please try this.
<td><g:checkBox name="registerBook" value="${bookInstance.id}" checked="false"/> </td>
Controller code for getting a list of selected books:
def checkedBooks = params.list('registerBook')
//get list of books. this will return only the selected books
def selectedBooks = Book.getAll(checkedBooks)
for(result in selectedBooks){
//now manipulate the result as you wish ...
}
+3
source to share