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

Cha*_*amp 6 jsp spring-mvc

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;

Dón*_*yle 8

这是必要的,因为您可能需要将多个复选框绑定到同一个字段,并且每个复选框都需要具有唯一ID.

例如,如果表单对象具有兴趣列表

Programming: <form:checkbox path="interests" value="Programming"/>
Painting: <form:checkbox path="interests" value="Painting"/>
Fishing: <form:checkbox path="interests" value="Fishing"/>
Run Code Online (Sandbox Code Playgroud)

输出将是:

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"/>
Run Code Online (Sandbox Code Playgroud)

(我省略了隐藏的空值输入)


Dan*_*roe 5

Donal是正确的,但如果您愿意,仍然可以在复选框上设置ID.

<label>
  <form:checkbox id="searchInSubject" path="searchInSubject"/>Subject
</label>
Run Code Online (Sandbox Code Playgroud)

然后你可以按照你期望的方式使用javascript.

if( $('#searchInSubject').prop("checked") ) {
  alert('checked');
}
Run Code Online (Sandbox Code Playgroud)