2011-12-12 18 views
12

En mis formularios HTML (como en la mayoría de los formularios HTML), las etiquetas comparten los mismos ID que los campos. Intento regresar al código HTML de la etiqueta una vez que se hace clic en la casilla de verificación con una ID coincidente.jQuery dado ID de entrada, obtener texto de etiqueta

<input id="yes1" type="checkbox"> 
<label for="yes1">This is the text it should return.</label> 

Y mi jQuery:

$('input').change(function() { 
    if (this.checked) { 
     var response = $('label#' + $(this).attr('id')).html(); 
    } 
} 

Pero, por desgracia, la respuesta sale como NULL.

+0

Estás buscando hasta 'etiqueta # yes1', pero no hay ningún objeto que coincide con el selector. – jfriend00

Respuesta

30
$('input').change(function() { 
    if (this.checked) { 
     var response = $('label[for="' + this.id + '"]').html(); 
    } 
}); 

No hay necesidad de obtener el ID del atributo .

Demostración: http://jsfiddle.net/wycvy/

-2

su sintaxis era un poco wacked, intente establecer el código HTML como tal

<input id="yes1" type="checkbox" /> 
<label for="yes1" id="yes1-label">This is the label</label> 

y luego usar jQuery al igual que

$("#yes1").click(function() { 
if ($("#yes1").is(":checked")) { 
    /* it's not really clear what you are trying to do here */ 
    var response = $("#label").attr("id"); 
    $("#yes1-label").text(response); 
} 
}); 
0

aquí es el ejemplo básico como por su exigencia. Necesita el contenido html de la etiqueta junto a su casilla de verificación, si está marcada.

uso de este

HTML

<div> 
<form > 
<input type="checkbox" id="yes" /><label for="yes">text yes </label> 
<input type="checkbox" id="no" /><label for="no">text no</label> 

</form> 


</div> 

JQUERY

$('input').change(function() { 
     if (this.checked) { 
      var response = $(this).next("label").html(); 
      alert(response); 
     } 
    }) 
Cuestiones relacionadas