Why does Spring MVC add β€œ1” to the path to create the form identifier: checkbox?

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

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

Why is "1" appended to the identifier? The reason I am asking is because I need to hard code "1" if I want to select this checkbox using javascript: document.getElementById('agreeToLegalAgreements1').checked=true;

+5
source share
2 answers

This is necessary because you may need to bind multiple checkboxes to one field, and each of them must have a unique identifier.

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 missed the hidden empty value input)

+7
source

, , .

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

javascript , .

if( $('#searchInSubject').prop("checked") ) {
  alert('checked');
}
+5

All Articles