Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: set label text
    primarykey
    data
    text
    <p>I'm trying to implement a generic function for a form with several fields in the following format.</p> <pre><code>&lt;label id="LblTextCount"&gt;&lt;/label&gt; &lt;textarea name="text" onKeyPress="checkLength(this, 512, LblTextCount)"&gt; &lt;/textarea&gt; </code></pre> <p>And the following JavaScript:</p> <pre><code>function checkLength(object, maxlength, label) { charsleft = (maxlength - object.value.length); // never allow to exceed the specified limit if( charsleft &lt; 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; } </code></pre> <p>The first part works fine, but I'm <b>not able to set the <code>charsleft</code>value into the label</b>. What am I doing wrong? Please note that I'm looking for a dynamic approach instead of hard coding the label name into the JS function. JQuery would be fine too :)</p> <p><hr> <b>Solution</b> - thanks to all!</p> <p>HTML</p> <pre><code>&lt;label id="LblTextCount"&gt;&lt;/label&gt; &lt;textarea name="text"&gt; &lt;/textarea&gt; </code></pre> <p>JS</p> <pre><code>$(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 &lt; 0 ) { obj.val(obj.val().substring(0, maxlength-1)); } // set the value of charsleft into the label $(label).html(charsleft); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload