2009-08-19 21 views
17

Sto cercando di implementare una funzione generica per un modulo con diversi campi nel seguente formato.Javascript: imposta il testo dell'etichetta

<label id="LblTextCount"></label> 
<textarea name="text" onKeyPress="checkLength(this, 512, LblTextCount)"> 
</textarea> 

E il seguente JavaScript:

function checkLength(object, maxlength, label) { 
    charsleft = (maxlength - object.value.length); 

    // never allow to exceed the specified limit 
    if(charsleft < 0) { 
     object.value = object.value.substring(0, maxlength-1); 
    } 

    // I'm trying to set the value of charsleft into the label 
label.innerText = charsleft; 
    document.getElementById('LblTextCount').InnerHTML = charsleft; 
} 

La prima parte funziona bene, ma io sono in grado di impostare il valore charsleft nell'etichetta. Che cosa sto facendo di sbagliato? Si prega di notare che sto cercando un approccio dinamico invece di codificare con difficoltà il nome dell'etichetta nella funzione JS. JQuery andrebbe bene :)


Soluzione - grazie a tutti!

HTML

<label id="LblTextCount"></label> 
<textarea name="text"> 
</textarea> 

JS

$(document).ready(function() { 
    $('textarea[name=text]').keypress(function(e) { 
     checkLength($(this),512,$('#LblTextCount')); 
    }).focus(function() { 
     checkLength($(this),512,$('#LblTextCount')); 
    }); 
}); 

function checkLength(obj, maxlength, label) { 
    var charsleft = (maxlength - obj.val().length); 

    // never allow to exceed the specified limit 
    if(charsleft < 0) { 
     obj.val(obj.val().substring(0, maxlength-1)); 
    } 

    // set the value of charsleft into the label 
    $(label).html(charsleft); 
} 

risposta

22

InnerHTML dovrebbe essere innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft; 

Si dovrebbe legare la vostra funzione checkLength al textarea con jQuery anziché richiamarla in linea e piuttosto intrusivamente:

$(document).ready(function() { 
    $('textarea[name=text]').keypress(function(e) { 
     checkLength($(this),512,$('#LblTextCount')); 
    }).focus(function() { 
     checkLength($(this),512,$('#LblTextCount')); 
    }); 
}); 

È possibile neaten fino checkLength usando più jQuery, e non vorrei usare 'oggetto' come un parametro formale:

function checkLength(obj, maxlength, label) { 
    charsleft = (maxlength - obj.val().length); 
    // never allow to exceed the specified limit 
    if(charsleft < 0) { 
     obj.val(obj.val().substring(0, maxlength-1)); 
    } 
    // I'm trying to set the value of charsleft into the label 
    label.text(charsleft); 
    $('#LblAboutMeCount').html(charsleft); 
} 

Quindi, se si applica quanto sopra, è possibile modificare la marcatura a:

<textarea name="text"></textarea> 
+0

C'è un modo elegante per legare anche checkLength() per onFocus rispettivo onpaste senza duplicare il contenuto del .ready $ (document) (funzione()) funzione? – MrG

+0

@MrG - È, guarda la mia modifica. Inoltre, non che l'evento paste non sia cross-browser. – karim79

+0

Tkx karim79, funziona perfettamente in una finestra separata (tutti i browser elencati di seguito) ma non riesce all'interno di una scheda dell'interfaccia utente JQuery senza errori nella console (FF/Safari/Opera non funziona, IE funziona correttamente). Hai un'idea? Molte molte grazie! – MrG

0

Per un approccio dinamico, se le etichette sono sempre davanti ai vostri aree di testo:

$(object).prev("label").text(charsleft); 
3

stai facendo diverse cose sbagliate. La spiegazione segue il codice corretto:

<label id="LblTextCount"></label> 
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')"> 
</textarea> 

Nota le virgolette intorno alla id.

function checkLength(object, maxlength, label) { 
    charsleft = (maxlength - object.value.length); 

    // never allow to exceed the specified limit 
    if(charsleft < 0) { 
     object.value = object.value.substring(0, maxlength-1); 
    } 

    // set the value of charsleft into the label 
    document.getElementById(label).innerHTML = charsleft; 
} 

Per prima cosa, durante l'evento di stampa tasto è necessario inviare l'id dell'etichetta come stringa per leggerlo correttamente. Secondo, InnerHTML ha un i minuscolo. Infine, poiché hai inviato la funzione id della stringa, puoi ottenere l'elemento con quell'id.

Fammi sapere come funziona per voi

EDIT Non che, non dichiarando charsleft come var, si sta implicitamente creando una variabile globale. un modo migliore sarebbe quello di fare quanto segue quando dichiarandolo nella funzione:

var charsleft = .... 
Problemi correlati