oncheck oyente para checkbox en javascript

2 minutos de lectura

Avatar de usuario de Gottfried Tetteh
Gottfried Tetteh

Tengo un código como este en la parte inferior de mi formulario.

<p>
  <input type="checkbox" id="agreed">
  I agree to keep my Username and Password confidential and uphold 
  the integrity of this pharmacy
</p>
<input type="submit" id="submit" disabled class="formbutton button-primary" value="Go">

Quiero que este sea un oyente en JavaScript para poder habilitar el botón de envío. Sé que podría estar mal o algo así, pero mi JavaScript se parece a esto

function track() {
    if ( document.getElementById("agreed").checked==true ) {
        document.getElementById("submit").removeAttribute("disabled");
    } else {
        document.getElementById("agreed").checked==false
    }
};

  • haz un js fiddle para mostrar lo que estás tratando de hacer

    – zgr024

    29 de julio de 2015 a las 16:08

  • ¿Qué tal si llamas al script cuando marcas la casilla? Ver stackoverflow.com/questions/3197702/…

    – thllbrg

    29 de julio de 2015 a las 16:08

  • El camino sucio… <input type="checkbox" id="agreed" onChange="track()"> y su asignación a las necesidades falsas uno =, no 2… document.getElementById("agreed").checked=false

    – zgr024

    29 de julio de 2015 a las 16:09


  • Si funciona, entonces no está mal, solo puede ser difícil de mantener si necesita hacer muchas comprobaciones.

    – html_programador

    29 de julio de 2015 a las 16:15

Avatar de usuario de Lvkz
Lvkz

Puedes hacer esto para la entrada:

<input type="checkbox" onchange="handleChange(this);">Checkbox

Y esto por habilitar el boton:

function handleChange(checkbox) {
    if(checkbox.checked == true){
        document.getElementById("submit").removeAttribute("disabled");
    }else{
        document.getElementById("submit").setAttribute("disabled", "disabled");
   }
}

  • hola amigo, gracias por tu respuesta. Este es mi primer proyecto con codificación y todo… estoy probando esto para un amigo. Gracias de todos modos funcionó.

    – Gottfried Tetteh

    29 de julio de 2015 a las 17:05

Avatar de usuario de Janty
Janty

Pruebe a continuación para su requerimiento usando jQuery.

$('#checky').click(function(){
     
    if($(this).attr('checked') == false){
         $('#postme').attr("disabled","disabled");   
    }
    else {
        $('#postme').removeAttr('disabled');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<input type="checkbox" checked="checked" id="checky"><a href="#">I agree to keep my Username and Password confidential and uphold 
  the integrity of this pharmacy</a>
<br>
<input type="submit" id="postme" value="submit">

Usando JavaScript, consulte este

¿Ha sido útil esta solución?