Skip to content Skip to sidebar Skip to footer

Jquery Keypress To Add Class

I am trying to learn jquery keypress to add class system. I have tryed the following code but it doesn't worked. I have tryed with an ID here. When started the #ttt1 then the the #

Solution 1:

You are defining a variable ID inside a function which occurs on $(document).ready(). Inside that function the value this will point to the document. What you need to do is to define the variable inside the keypress event handler function.

Use class for selection and then use $(this).attr("id") inside the handler function. Also you can use $(this).closest('div').next() to get the next element in the parent.

DEMO

$(document).ready(function() {
   //here  value for this is the document object and the id is not useful.
   $(".test").on('keyup', function() {
     //but here value for this is textarea where keypress event happened.varID = this.id;
      if (this.value.length > 20) {
         $(this).closest('div').next().addClass("ad");
      } else {
         $(this).closest('div').next().removeClass("ad"); 
      }
   });
});
.container {
   margin:0px auto;
   width:100%;
   max-width:500px;
   position:relative;
   margin-top:100px;
}

.test {
   outline:none;
   border:1px solid red;
   width:100%;
   min-height:100px;
}
.br {
   background-color:blue;
   width:100px;
   height:40px;
}
.ad {
   background-color:red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><divclass="container"><divclass="tWrp"><textareaclass="test"id="ttt1"placeholder="Write"></textarea></div><divclass="br"id="rb1">Button</div></div><divclass="container"><divclass="tWrp"><textareaclass="test"id="ttt2"placeholder="Write"></textarea></div><divclass="br"id="rb2">Button</div></div>

Post a Comment for "Jquery Keypress To Add Class"