Monday, 27 July 2015

Change the color to red if text exceeds the limit in textarea using jQuery

Leave a Comment

First we should know that by using maxlength attribute in textarea we can limit the characters without using any additional coding.

Here is the code for maxlength attribute in textarea. Click here for demo.

<textarea rows="4" cols="50" maxlength="15">
Enter text here...</textarea>

For our example lets create a simple textarea with cols=”20” and rows=”5”, give it an id="mytextarea".

<textarea id="mytextarea" cols="20" rows="5"></textarea>

Now the jQuery part, add the jquery library and we will start coding.

$("#mytextarea").keyup(function(){

var maxlength = 15; // specify the maximum length

if($("#mytextarea").val().length > maxlength){
$("#mytextarea").css('color','red');
}
else{
$("#mytextarea").css('color','black');
}
});

In the above code keyup event occurs whenever key is released. So we are calling anonymous function whenever key is released. We are limiting text in textarea to 15 characters ie maxlength. If text in textarea is greater than 15 ie maxlength, then change text color to red else black. Everything is self explanatory. That’s it.


Let’s look at full code.

<textarea id="mytextarea" cols="20" rows="5"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="JavaScript"><!--
$("#mytextarea").keyup(function(){
var maxlength = 15; // specify the maximum length
if($("#mytextarea").val().length > maxlength){
$("#mytextarea").css('color','red');
}
else{
$("#mytextarea").css('color','black');
}
});
</script>

0 comments:

Post a Comment

.