Вопрос

I asked an earlier version of this question and learned to use .css to change the class. However, I decided I'd rather use addClass and removeClass (it would make it easier for later functions I'm going to bring in).

Here is the code, and jsfiddle:

$(function(){
   if($.trim($('.text-edit1').val()).length){
      $(this).addClass('active-text');
   });
});

All I want to do is add a background color when the user types into the textarea, and remove the color when the text is deleted. I tried to write the beginning of the function but can't get it to work...

It would be great if anyone knew how to do this. Thanks in advance!

Это было полезно?

Решение

If you want to write $(this) you have to attach an event to the element. Looks like you need a keyup event.

$('.text-edit1').keyup(function () {
    if ($.trim($('.text-edit1').val()).length) {
        $(this).addClass('active-text');
    } else {
        $(this).removeClass('active-text');
    }
});

http://jsfiddle.net/gEVL9/4/

Другие советы

You can also try to attach an keyup event handler with jquery .on()

$(function(){
    $(document).on('keyup','.text-edit1',function(){
       if ($.trim($('.text-edit1').val()).length) {
        $(this).addClass('active-text');
       }
       else {
        $(this).removeClass('active-text');
      }
    });
});

Try in fiddle

Just a bit shorter variant, less readable.

$('.textarea-class').on('keyup', function (ev) {
    $(this).toggleClass('active', !!$(this).val().trim());
});

!! - will convert value to it's boolean representation

.toogleClass(class, state) - state "true" - class will be added, state "false" - removed

trimmed empty string '' will be handled as falsy, so class will be removed

JSFiddle Demo

Use keyup event

$('.text-edit1').keyup(function () {
    if ($.trim($(this).val()).length) {
        $(this).addClass('active-text');
    }else {
        $(this).removeClass('active-text');
    }
});

DEMO

You can bind keyup event with textarea.

$('.text-edit1').bind('keyup',function () {
    if ($.trim($(this).val()).length) {
        $(this).addClass('active-text');
    }else {
        $(this).removeClass('active-text');
    }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top