How not to select more than 1 checkbox, jquery?

0

I have the following validation:

var contador = 0;

if (contador>0){
           console.log("no se puede seleccionar mas checkbox");
           $(this).removeAttr('checked');
           console.log(contador);
        }
        else{
            if ($(this).is(':checked')){
                console.log("Esta chequeado");
                console.log(numero_prestamo);

               /* prestamo_seleccionado.NumeroDocumento = 
                prestamo_seleccionado.Monto = 
                prestamo_seleccionado.Tipo_Prestamo =
                prestamo_seleccionado.NumeroPrestamo =
                prestamo_seleccionado.Cod_Fiador = */
                contador++;
                console.log(contador);
            }
            else{
                console.log("No esta chequeado");
                prestamo_seleccionado = {};
                contador--;
                console.log(contador);

            }
        }

and basically what I need to do is not allow me to select more than 1 checkbox.

Thank you very much.

    
asked by JG_GJ 21.11.2018 в 00:17
source

1 answer

1

I add a% html of example, in the following function all the boxes of those that are type checkbox are evaluated, the .prop is used to obtain the value of the first coincidence that it finds (in this case set the property "checked"):

$("input:checkbox").on('click', function() {
  var box = $(this);
  if (box.is(":checked")) {
    var group = "input:checkbox[name='" + box.attr("name") + "']";
    $(group).prop("checked", false);
    box.prop("checked", true);
  } else {
    box.prop("checked", false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>Frutas</h3>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Manzana</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Naranja</label>
  <label>
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>

I hope it helps you. Greetings.

    
answered by 21.11.2018 / 00:32
source