He escrito una función jQuery para limitar la selección de la casilla de verificación a 4 elementos, el problema es: ¡solo funciona con la entrada de etiquetas por sí misma! pero cuando pongo esta etiqueta dentro de una o dentro de una tabla, ¡no funciona!
He intentado eliminar la etiqueta, hace que el método jQuery funcione sin problemas, pero en la implementación necesito esta etiqueta para mostrar mis elementos en una tabla.
Este es mi código html:
<c:forEach var="tempVehicles" items="${vehicleList}">
<tr>
<c:choose>
<c:when test="${tempVehicles.vehicleType eq vehicleType}">
<td>${tempVehicles.registration} </td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}"/></td>
</c:when>
</c:choose>
</tr>
</c:forEach>
Y mi código jQuery:
$('input[type=checkbox]').on('change', function() {
var limit = 4;
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
Con este código, puedo seleccionar más de 4 elementos "el método jQuery no funciona", pero cuando elimino la etiqueta <td>
de la entrada, el método realmente funciona.
3 respuestas
Como sus entradas no son hermanos, cambie el selector para verificar cuántos están seleccionados como en el siguiente código
$('input[type=checkbox]').on('change', function() {
var limit = 4;
if($('.single-checkbox:checked').length >= limit) {
this.checked = false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table><tr>
<td><input class="single-checkbox" type="checkbox" value="1"/></td>
<td><input class="single-checkbox" type="checkbox" value="2"/></td>
<td><input class="single-checkbox" type="checkbox" value="3"/></td>
<td><input class="single-checkbox" type="checkbox" value="4"/></td>
<td><input class="single-checkbox" type="checkbox" value="5"/></td>
<td><input class="single-checkbox" type="checkbox" value="6"/></td>
<td><input class="single-checkbox" type="checkbox" value="7"/></td>
Parece que las entradas son elementos secundarios de td
s, no son hermanos, por lo que .siblings
no va a seleccionar los elementos correctos.
Si todos tienen la misma clase de single-checkbox
, coloque los .single-checkbox
en una colección jQuery y, en la devolución de llamada, verifique si la longitud de esa colección, filtrada por :checked
, es mayor que limit
:
const $singleCheckbox = $('input.single-checkbox');
$singleCheckbox.on('change', function(e) {
var limit = 4;
if ($singleCheckbox.filter(':checked').length > limit) {
this.checked = false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
<td><input class="single-checkbox" type="checkbox" id="vIds[]" name="vIds[]" value="${tempVehicles.id}" /></td>
</tr>
</table>
Puede imponer un límite de verificación yendo al padre y luego volviendo a consultar a sus hijos.
(($) => {
$.fn.checkLimit = function(limit) {
this.on('change', function(e) {
let $parent = $(this).parent();
let $target = $parent.prop('tagName') === 'LABEL' ? $parent.parent() : $parent;
if ($target.find(':checked').length > limit) {
this.checked = false;
}
});
}
})(jQuery);
$('input[name="vIds[]"]').checkLimit(4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Mark-up via: https://www.dyn-web.com/tutorials/forms/checkbox/same-name-group.php -->
<form action="#" method="post" class="demoForm" id="demoForm">
<fieldset>
<legend>Demo: Checkboxes Sharing Same Name</legend>
<p>Check the types of sports or fitness activities you engage in on a regular basis.</p>
<p>
<label><input type="checkbox" name="vIds[]" value="cycling" /> cycling</label>
<label><input type="checkbox" name="vIds[]" value="running" /> running</label>
<label><input type="checkbox" name="vIds[]" value="visit gym" /> visit gym</label>
<label><input type="checkbox" name="vIds[]" value="swimming" /> swimming</label>
<label><input type="checkbox" name="vIds[]" value="team sports" /> team sport(s)</label>
<label><input type="checkbox" name="vIds[]" value="other" /> other</label>
</p>
</fieldset>
</form>
Preguntas relacionadas
Nuevas preguntas
javascript
Para preguntas sobre la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excepto ActionScript). Incluya todas las etiquetas relevantes en su pregunta; por ejemplo, [node.js], [jquery], [json], etc.