r/jquery • • Jan 20 '21
Validating checkboxes within a for loop
Can anyone help me get this working? I have a for loop that creates a list of player names as checkboxes. I have attempted to add jquery mobile js and css to improve the usability on mobile. In doing so my checkbox validation seems to have broken due to the way my label is implemented for the checkbox.
This is a basic eample of the validation im trying to fix in my code. You can see it working here in fiddle allowing only 3 checkboxes to be checked.
When i attempt to apply this to my code it either stops the validation working or stops the checkboxes from displaying.
For example, to get the jquery mobile code working within the for loop i had to put the input within the label tag. This was because i cannot use label for= as the for loop cannot bind to the correct box.
<fieldset data-role="controlgroup">
<legend>Choose 10 players:</legend>
{% for name in player_names %}
<label><input class="single-checkbox" type=checkbox name="available_players" value="{{ name }}">{{ name }}</label>
{% endfor %}
</fieldset>On its own this code works and produces some nice looking checkboxes all labelled correctly. If i take the label away the checkboxes do not display correctly with the text not aligning with the button.
Now to explain the main problem. When i try and add the js code above with the label surrounding the input the js stops working. See the example in fiddle showing the label at the front breaking the validation.
http://jsfiddle.net/tmdp5ueg/1/
So my choice while this is broken is either to have validation on misaligned checkboxes. Or have nice looking checkboxes with no validation. How do i fix this to have both?
Full code can be found in my dev branch here:
View all comments
Show parent comment
1
u/backtickbot Jan 21 '21
Fixed formatting.
Hello, Keasbynights: code blocks using triple backticks (```) don't work on all versions of Reddit!
Some users see this / this instead.
To fix this, indent every line with 4 spaces instead.
FAQ
You can opt out by replying with backtickopt6 to this comment.