Alejandro Hinestrosa
Alejandro Hinestrosa

Reputation: 501

checkbox validation using jquery

I'm searching a while for this and I can't found something that works for me.

I have this checkbox:

 <%= Html.CheckBox("cbCodigo") %> <label class="inline" for="Codigo">Codigo</label>
 <%= Html.CheckBox("cbNombreCliente") %> <label class="inline" for="NombreCliente">Nombre del cliente</label>
 <%= Html.CheckBox("cbCiudad") %> <label class="inline" for="Ciudad">Ciudad</label>

I want to validate that only one is checked when a textbox change, something like this, and use .validate of jQuery, I don't what is the best way for validate this.

tbCodCliente is a textbox that I use as a search parameter, and the checkbox is a parameter or a value for the autocomplete function of the textbox

$('#tbCodCliente').change(function() {
     if ($('#cbCodigo').attr('checked', false) &&
          $('#cbNombreCliente').attr('checked', false) &&
          $('#tbCheckbox').attr('checked', false)) {

          // function for validate method          
     }
});

I trying to validate of this way, but I don't know if it is the best way.

EDIT: I want something like this, but still can found how make it works

('#tbCodCliente').change(function() {
    if( $("input:checked").length == 0 ) {
        $("#request-form").validate({
             rules: {
                 checkbox: { 
                     required: 'input[type="checkbox"]:checked',
                     minlength: 1
                 }   
             },
             messages: {
                 checkbox: {"Please check at least one."}
             }
        })        

    }
});

Upvotes: 0

Views: 5462

Answers (2)

codef0rmer
codef0rmer

Reputation: 10530

This will uncheck other checkboxes once any single checkbox is checked.

$('input:checkbox').change(function () {
        if (this.checked) {
            $('input:checkbox:not(#'+this.id+')').attr('checked', false);
        }
}); 

Demo: http://jsfiddle.net/5btfe/

And for single-checkbox-selected check you can refer epuri's answer which is quite correct.

Upvotes: 1

Epuri
Epuri

Reputation: 300

If these are the only checkboxes available on the page then you can try following jQuery statement to check:

if( $("input:checked").length == 1 )

Edit:

To be more precise, you can change the validation code to following:

$('#tbCodCliente').change(function() {
   if( $("input:checked").length == 1 ) {
       //Do stuff here
   }
});

Upvotes: 2

Related Questions