jeudi 20 juin 2019

Spring Boot Checkbox Array not working as expected

I have an array of checkboxes all with the same names which I submit to a Spring Boot Controller. I build a Bootstrap DataTable using Jquery/Ajax using data which receive from the database and test if I should select the checkbox when the page loads. I do this by using this code:

if (data['isChecked'] == "1") {
   return "<input type='checkbox' name='fieldIdList' value='1_' checked>";
} else {
   return "<input type='checkbox' name='fieldIdList' value='1_'>";
}

This code loops, so the next checkbox value will be 2_ and the next 3_, etc, etc.

When the page loads the table displays 10 rows and my first 2 checkboxes are shown as selected. This is correct.

Now when I submit this form without changing the state of any of the checkboxes to my Controller code below:

@RequestMapping(value = "/admin/dataTable", method = RequestMethod.POST)
public String postDataTable(@RequestParam("fieldIdList") List<String> fieldIdList){
    return "";
}

I get 2 entries in my fieldIdList:

"1_"

"2_"

This is correct because only my first 2 checkboxes was checked. But when I uncheck any of the checkboxes and submit again, I get a funny result. In the example below, I unchecked the 2nd checkbox and then submitted the form again, my entries in my fieldIdList:

"1_"

"1_"

"1_"

"2_"

By unchecking the second checkbox and submitting, I suspected to get only 1 entry in my fieldIdList as "1_"

Also after I submit, the page is redirected the the previous page, so when I enter this page again, all the Lists are loaded as new, so there can be no previous values still stored in them.

Not sure if this is a Jquery/Ajax issue or Java issue or just a problem with the object between the chair and laptop :)

Thank you for your time.




Aucun commentaire:

Enregistrer un commentaire