Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Spring MVC appends a "1" to the path to generate id of form:checkbox?

Tags:

spring-mvc

jsp

If I have a checkbox like this in my jsp: <form:checkbox path="agreeToLegalAgreements" />

It results in: <input id="agreeToLegalAgreements1" name="agreeToLegalAgreements" type="checkbox" value="true"/><input type="hidden" name="_agreeToLegalAgreements" value="on"/>

Why is a "1" being appended to the id ? The reason I ask is because I have to hardcode the "1" if I want to select this checkbox using javascript: document.getElementById('agreeToLegalAgreements1').checked=true;

like image 725
Champ Avatar asked Jan 10 '10 02:01

Champ


2 Answers

This is necessary as you may need to bind multiple check boxes to the same field and each will need to have a unique id.

For example, if your form object has a list of interests

Programming: <form:checkbox path="interests" value="Programming"/>
Painting: <form:checkbox path="interests" value="Painting"/>
Fishing: <form:checkbox path="interests" value="Fishing"/>

The output will be:

Programming: <input id="interests1" name="interests" type="checkbox" value="Programming"/>
Painting: <input id="interests2" name="interests" type="checkbox" value="Painting"/>
Fishing: <input id="interests3" name="interests" type="checkbox" value="Fishing"/>

(I have omitted the hidden empty value input)

like image 172
Dónal Boyle Avatar answered Sep 25 '22 10:09

Dónal Boyle


Donal is correct, however you can still set the ID on the checkbox if you want to.

<label>
  <form:checkbox id="searchInSubject" path="searchInSubject"/>Subject
</label>

Then you can use javascript in the way you'd expect.

if( $('#searchInSubject').prop("checked") ) {
  alert('checked');
}
like image 38
DanMonroe Avatar answered Sep 21 '22 10:09

DanMonroe