Issue
I am very new to spring mvc world. I am trying to send boolean value to from html form checkbox. When a user check the checkbox then it will send true, false otherwise.
<form class="attendanceBook" role="form" method="post" action="/attendances">
<div class="row">
<div class="form-group">
<div class="col-xs-4">
<label class="control-label">Check Here</label>
</div>
<div class="col-xs-4">
<input type="checkbox" name="i" id="i" value="true" />
</div>
<div class="col-xs-4">
<input type="submit" value="Click"/>
</div>
</div>
</div>
</form>
After some googilng I have found this so post, where it said standard behaviour is the value is only sent if the checkbox is checked.
So what I have understand that is if the checkbox checked then the form will submit with the value of checkbox, otherwise it will not submit. When there is unchecked checkbox the initialization value in data class will be effective.
But in my case every time I am submitting the form it submitting true
.
here is my rest controller for the bind html form submit.
@RestController
@RequestMapping("attendances")
class AttendanceRestController {
val logger = getLogger(AttendanceRestController::class.java)
@PostMapping
fun patchAttendance(@RequestBody attendanceJson: AttendanceJson): ResponseEntity<*> {
logger.info("attendanceJson {}", attendanceJson)
return responseOK(attendanceJson)
}
}
the data class(I am using kotlin)
data class AttendanceJson (
var i: Boolean = false,
var t: String = ""
)
So what will be the method to bind boolean data from a form submission with checkbox. I am also using Thymeleaf
. Thanks in advance.
Solution
I'm working in Struts and don't know much about Spring. But I faced a similar situation.
What I did was I binded the checkbox with a boolean property in my From class. So for each checkbox, one boolean variable. And at the time of submitting in front end, I'll call a JS function code is below
function verifyCheckboxes() {
document.getElementById("researchPaper").value = document.getElementById("researchPaper").checked;
document.getElementById("researchPaperSeminarProceed").value = document.getElementById("researchPaperSeminarProceed").checked;
document.getElementById("extraActivities").value = document.getElementById("extraActivities").checked;
document.getElementById("studentAchivements").value = document.getElementById("studentAchivements").checked;
}
Here you can see I'm just assigning the value of checked property of that Checkbox just before submitting. It will be either true or false.
Answered By - Arun Sudhakaran