Entonces, ¿cómo puedo permitir que un usuario sólo seleccione una casilla de verificación?
Sé que los botones de radio son "ideales", pero para mi propósito' no lo es.
Tengo un campo en el que los usuarios deben seleccionar una de las dos opciones, pero no ambas. El problema es que necesito que mis usuarios también puedan deseleccionar su opción, y aquí es donde los botones de radio fallan porque una vez que seleccionas el grupo, tienes que elegir una opción.
Voy a validar la información a través de php, pero todavía me gustaría restringir a los usuarios a una sola respuesta si quieren darla.
Este fragmento lo hará:
begin snippet: js hide: false -->
// the selector will match all input controls of type :checkbox
// and attach a click event handler
$("input:checkbox").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = "input:checkbox[name='" + $box.attr("name") + "']";
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<h3>Fruits</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
<h3>Animals</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>
Fin del fragmento;
$("#myform input:checkbox").change(function() {
$("#myform input:checkbox").attr("checked", false);
$(this).attr("checked", true);
});
Esto debería funcionar para cualquier número de casillas de verificación en el formulario. Si tiene otras que no forman parte del grupo, configure los selectores de las entradas correspondientes.