labu77 labu77 - 27 days ago 9
HTML Question

Use Jquery text().length inside of a textarea

I found this usefull text counter by css class.

$(".quotecontent").filter(function() {
return $(this).text().length < 40;
}).parent().css('background', 'red');


http://jsfiddle.net/adeneo/kh8Hh/

When arround the container is a textarea, the jquery code is not working anymore. Any Ideas?

See:

http://jsfiddle.net/e1j7xqsx/

thank you

Answer

If you examine the content of your textarea, you'll see that there is no DOM elements there:

    <textarea>
    &lt;div class="quote"&gt;
    &lt;div class="quotestart"&gt;&lt;/div&gt;
    &lt;div class="quotecontent"&gt;&lt;p&gt;We have a new toy!&lt;/p&gt;
    &lt;div class="author"&gt;- Fernando Alonso&lt;/div&gt;&lt;/div&gt;
    &lt;div class="quoteend"&gt;&lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="quote"&gt;
    &lt;div class="quotestart"&gt;&lt;/div&gt;
    &lt;div class="quotecontent"&gt;&lt;p&gt;Fight to fly, fly to fight, fight to win.&lt;/p&gt;
    &lt;div class="author"&gt;- Motto of the U.S. Navy Fighter Weapons School, TOPGUN&lt;/div&gt;&lt;/div&gt;
    &lt;div class="quoteend"&gt;&lt;/div&gt;
    &lt;/div&gt;
    </textarea>

All the content inside textarea is text. So this $(".quotecontent").length is 0.

One solution could be to have a separate DOM element acting as error containers, and you can show div's with errors there:

var errorWrapper = $('.error-wrapper');
errorWrapper.html($('textarea').text());

$(".quotecontent").filter(function() {
    return $(this).text().length < 40;
}).parent().css('background', 'red');

$(".quotecontent").filter(function() {
    return $(this).text().length > 40;
}).parent().remove();