tags:

views:

367

answers:

6

Does anyone know a way to detect when a given element's class has changed using JQuery?

I'm using the "simply countable" JQuery plug-in to notify the user of the number of characters entered into a text area. When the user exceeds the allowed number of characters, I would like to disable the "post" button.

Since simply countable changes the assigned CSS class when the limit is reached, my idea was to capture that event so that I could disable the post button, but perhaps there is a better way?

Any suggestions are welcome.

Thanks.

A: 

I do not know of anything that currently exists, but you could write a plugin to jQuery that fires a custom event whenever the class name is modified (via jQuery).

geowa4
A: 

You can try jQuery Validation Plugin.

Daniel Moura
A: 

You could have an event on keypress or up (for the text area) that checks to see if the maximum number of characters has been reached, and fire off appropriate logic.

$(textarea).keypress(function (e) {
       if(getLetterCount() > 300){
           $(postButton).css('disabled', 'true');
       else
           $(postButton).css('disabled', 'false');
       }
 });
Mark Rogers
+1  A: 

Assuming you need to block the control, not to intercept the class change, you can just rewrite the plugin part responsible for action (class addition).

ilya.devyatovsky
A: 

There's no such event. What you need to do is tweak the plugin to fit your needs.

Go look through the code. Anywhere it calls addClass(options.overClass) you need to disable your button. Anywhere it calls addClass(options.safeClass) you need to enable your button. Simple.

Josh Stodola
A: 

Do you mean something like this?

<script>
   $("#myTextArea").change(function(){
       var contentLength = $(this).val().length; 
       var charLimit = 500;
       if(contentLength > charLimit){
           $("#saveButton").attr("disabled","disabled");
       }

   });

</script>


<textarea id="myTextArea"></textArea>
<input type="submit" id="saveButton">
Scott
I basically went with this (except I used "keyup" event rather than "change"). Originally, I wanted to avoid having to set the max char count in both the character counter AND in the button disabling code above, but all of the options seemed too hackish. Thanks.
goombaloon