Victor York
Victor York

Reputation: 1681

How to get each checked checkbox using jQuery

I have the following:

PHP/HTML CODE:

<?php
$c = 1;
    foreach($this->contactos as $contacto){
?>
        <div class="uk-form-row">
        <label for="contactopadrino<?php echo $c; ?>" class="uk-form-label"><?php echo $contacto->email; ?></label>

        <input class="contactopadrinos" name="contactopadrino[]" id="contactopadrino<?php echo $c; ?>" type="checkbox" value="<?php echo $contacto->email; ?>" />
        </div>

<?php 
$c++;
}
?>      

jQuery CODE:

     function validarEnviarDescuento(){  
        $('#errorofertacontainerdescuento').css('display','none');
        $('#errorofertadescuento').html('');
        var validar = 0;
        var vacio = 0;
        for(var e=1; e<6; e++){
            var email = $("#email_contactopadrino"+e).val();    
            if(!validarEmail(email) && email != ''){
                validar++;
            }
            if(email != ''){
                vacio++;
            }
        }

        if(!vacio){
             $('input:radio:checked').each(function () { 
                var $this = $(this);

                if ($(this).prop('checked')) {
                    return true;
                }
            });

            $('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_SIN_SELECCIONAR'); ?>' + '</li>');
            $('#errorofertacontainerdescuento').css('display','block');
            return false;
        }
        if(validar){ 
            $('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_EMAIL_INCORRECTO'); ?>' + '</li>');
            $('#errorofertacontainerdescuento').css('display','block');
            return false; 
        }
        else{ 
            return true; 
        }

 }

Im trying to go through each input and if one is checked it should return true and submit but what I have done is not working.

Upvotes: 0

Views: 84

Answers (2)

Satpal
Satpal

Reputation: 133403

You don't need to use each. instead use cobination :checked and length

return $('input:checkbox:checked').length;

It will return true if anyone of the checkbox button has checked

Upvotes: 1

Adil
Adil

Reputation: 148110

You can use :checked with selector to get all radio buttons those are checked.

$('input:radio:checked')

Description: Matches all elements that are checked or selected, jQuery docs

If you want to check if atleast one radio is checked then you can use length

if($('input:radio:checked').length)
{
}

For iterating through checked radio you can use each

$('input:radio:checked').each(function(){
  alert(this.value);
});

Upvotes: 1

Related Questions