I have created HTML checkboxes in a JSP loop and I wish to do validation for those checkboxes in JavaScript, how should I do that?
Normally, for a single object, we can do it like window.document.form.checkbox
or something similar.
Not sure about checkboxes appearing in loop.
<%
for(int i=1; i<somevalue; i++) //jsp
{
%>
<input type="checkbox" name="chkbox_"<%=i> value="<%=something%>">
<!-- html -->
<%
}
%>
I have created HTML checkboxes in a JSP loop and I wish to do validation for those checkboxes in JavaScript, how should I do that?
Normally, for a single object, we can do it like window.document.form.checkbox
or something similar.
Not sure about checkboxes appearing in loop.
<%
for(int i=1; i<somevalue; i++) //jsp
{
%>
<input type="checkbox" name="chkbox_"<%=i> value="<%=something%>">
<!-- html -->
<%
}
%>
Share
Improve this question
edited Sep 12, 2024 at 11:49
Mark Schultheiss
34.2k12 gold badges72 silver badges113 bronze badges
asked Nov 28, 2014 at 18:19
hadeshades
4,73410 gold badges52 silver badges78 bronze badges
2 Answers
Reset to default 1According to me, we have some solutions:
- If you don't want to modify HTML code and using Javascript. You can use this method
getElementsByTagName
- Example
var checkboxes = document.getElementsByTagName("input");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") {
var isChecked = checkboxes[i].checked;
}
}
Add
class
attribute for all checkbox and use this methodgetElementsByClassName
Add
id
attribute for each checkbox and usegetElementById
methodUse JQuery
$("input[type=='checkbox']").each(obj, function(key, value) {
// Do something
});
It looks like your loop ends prematurely i.e. <
instead of <=
, since you are starting at 1
. Also, you did not close your name
attribute correctly.
Note: You should include your outer <form>
.
<form name="checkbox-form">
<% for (int i = 1; i <= checkboxCount; i++) { %>
<input type="checkbox" name="chkbox_<%=i%>" value="<%=something%>">
<!-- html -->
<% } %>
</form>
You can query for checkboxes within the form via:
const form = document.forms['checkbox-form'];
const checkboxes = form.querySelectorAll('input[type="checkbox"]');
Alternatively, select them by their name:
const form = document.forms['checkbox-form'];
const checkboxes = form.querySelectorAll('[name^="chkbox_"]');
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744762234a4592240.html
评论列表(0条)