madcrazydrumma madcrazydrumma - 6 months ago 11
Javascript Question

Updating a character limit count on my textarea

So I've created my textarea here:

textarea {
min-width: 120px;
min-height: 90px;
padding: 8px 10px;
background: #FFF;
border: 1px solid #E0E0E0;
border-radius: 2px;
outline: none;
padding: 8px 10px;
box-shadow: inset 0 1px 2px rgba(#E0E0E0, .50), 0 -1px 1px #FFF, 0 1px 0 #FFF;

@include transition(all .2s ease-in-out);

@include placeholder {
font-family: 'Titillium Web', sans-serif;
}
}
textarea:focus {
border: 1px solid lighten(#3498db, 10);

@include box-shadow(0px, 0px, 6px, rgba(lighten(#3498db, 10), .5), false);
}
.textarea-group {
position: absolute;
min-width: 120px;
min-height: 90px;

textarea[limit] {
display: block;
resize: none;
border-bottom: none;
border-bottom-left-radius: 0; border-bottom-right-radius: 0;
margin: 0;
position: relative;
width: 100%;
}
.chars {
display: block;
margin: 0;
position: relative;
width: 100%;
padding: 8px 10px;
background: #FAFAFA;
color: #999;
font-size: 11px;
border: 1px solid #E0E0E0;
border-bottom-left-radius: 2px; border-bottom-right-radius: 2px;
}
}


And I've written a script to detect changes in my code, however it is not updating my counter. Can anyone tell me why? I think it may be due to the selection of the elements.

$(function() {
$('.textarea-group > textarea[limit]').keyup(function() {
var max = $(this).attr('limit');
var length = $(this).val().length;
length = max - length;
$(this + ' > .chars span').text(length);
});
});


The script definitely gets called.

N.B. I want this to apply to all elements individually that have the same name :)

Thanks!

EDIT The final code for jquery is shown below:

$(function() {
$('.textarea-group > textarea[limit]').keyup(function() {
var max = parseInt($(this).attr('limit'));
var length = $(this).val().length;
length = max - length;
$('.chars span', $(this).parent()).html(length);
});
});


Credits to Francisco (answer) and Akshay (integer parse)

Answer

this is not a string, so this should fail:

$(this + ' > .chars span')

In adition, this should be the gextarea, so first you have to travel one level up the DOM.

Instead, try using the second parameter context:

$('.chars span', this.parentNode)

Or use parent and find:

$(this).parent().find('.chars span')