Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

51
Vistas
Why isn't my checkbox change event triggered?

I have two functions.

The first function translates a div click into a checked/unchecked toggle. The second function translates a checkbox change into a hide/show event.

The problem is that when I use the first function to check/uncheck the box, the second function is not called. I am new to javascript, thanks.

<script type="text/javascript">
$(document).ready(function() {
    $(":checkbox").parent().click(function(evt) {
        if (evt.target.type !== 'checkbox') {
            var $checkbox = $(":checkbox", this);
            $checkbox.attr('checked', !$checkbox.attr('checked'));
            evt.stopPropagation();
            return false;
        }
    });
});
</script>

<script type="text/javascript">
$(document).ready(function() {
    $(":checkbox").change(function() {
        if($(this).attr("checked")) {
            $('.'+this.id).show();
        }
        else {
            $('.'+this.id).hide();
        }
    });
});
</script>
8 months ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

The change event does not fire when you programmatically change the value of a check box. What you can do to ensure it fires is:

 $(":checkbox").parent().click(function(evt) {
    if (evt.target.type !== 'checkbox') {
        var $checkbox = $(":checkbox", this);
        $checkbox.attr('checked', !$checkbox.attr('checked'));
        $checkbox.change();
    }
});
8 months ago · Santiago Trujillo Denunciar

0

Don't bother with the first snippet. Just use LABEL elements:

<label><input type="checkbox">Some option</label>

Now, when the user clicks the label (the text next to the checkbox), the checkbox will be activated.


The second snippet can be optimized:

$('input:checkbox').change(function() {
    $('#' + this.id).toggle(this.checked);
});
8 months ago · Santiago Trujillo Denunciar

0

you are using '.' which is for class selectors instead use '#' since you are using the element ID. Like this:

$(document).ready(function() {
    $(":checkbox").bind('change', function() {
        if($(this).attr("checked")) {
            $('#'+this.id).show();
        }
        else {
            $('#'+this.id).hide();
        }
    });
});
8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos