2010-04-15 25 views
30

Me falta algo obvio aquí ... No puedo obtener .change() para disparar botones de radio? Tengo el siguiente código en vivo here!jQuery .change() en el botón de radio

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Radio Button jQuery Change</title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     console.log("parsed"); 
     $("input[name='rdio']").change(function() { 
      console.log("changed"); 
      if ($("input[name='rdio']:checked").val() == 'a') 
       $("output").text("a changed"); 
      else if ($("input[name='rdio']:checked").val() == 'b') 
       $("output").text("b changed"); 
      else 
       $("output").text("c changed"); 
     }); 
    </script> 
</head> 
<body> 
    <div> 
     <input type="radio" name="rdio" value="a" checked="checked" /> a <br/> 
     <input type="radio" name="rdio" value="b" /> b <br/> 
     <input type="radio" name="rdio" value="c" /> c 
    </div> 
    <h3>Output:</h3> 
    <div id="output"></div> 
</body> 
</html> 

¿Alguien puede ver lo que me he perdido?

Gracias, Denis

+8

... al menos el '#' en '$ (" salida ")' ... – Leo

+0

también puede usar this.value en su lugar "input [name = 'rdio']: checked"). Val() . Será más eficiente. – Yaroslav

+0

Aquí está el documento sobre el contexto 'this' https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Yaroslav

Respuesta

41

debe poner el código dentro del evento dom-listo ...

$(document).ready(function(){ 
    // Your code here 
}); 

o bien el script se ejecuta antes de que se han cargado los elementos HTML. Por lo tanto, no existen radios.

+1

¡Muchas gracias por publicar esto! –

15

Su

$("output").text("a changed"); 

también debe ser

$("#output").text("a changed"); 

porque es un identificador que son coincidentes en contra.