marck
marck

Reputation: 143

Events after keypresses (jquery)

I have a textarea. After the user types X number of characters in the textarea I want a few different events to fire.

I know I can use keypress events in jquery, but how can I set off a event after say 25 characters have been typed?

I'm current trying this:

$('#post-content-field').keyup(function () {
$('#post-title-field').val($("#post-content-field").val()).trigger('change');
                            });

Upvotes: 0

Views: 4374

Answers (4)

Sampson
Sampson

Reputation: 268344

You can check the .length of the value of the textarea after each keypress. If it is greater than or equal to 25, grab the first few characters and increase the textarea height.

$("textarea.affectMe").on("keyup", function(){
  if ( this.value.length >= 25 && !$(this).hasClass("done") ) {
    $(this).addClass("done");
    $(".threeChars").val( this.value.substring(0,25) );
  }
});

Note, I'm adding a class to the textarea so we don't do this over and over after each keypress when the length is greater than 25.

Demo: http://jsbin.com/afonar/edit#javascript,html

Upvotes: 2

Imdad
Imdad

Reputation: 6032

That was for your reference you can do anything you like. Remove the lines that stops you from adding more text

refer below

function countChar(val){
    var len = val.value.length;
     $('#charNum').text(len);
     if (len >= 500) {
                     // Copy
      }else {
            //DO anything
      }
};

Upvotes: 1

Imdad
Imdad

Reputation: 6032

Use jquery and the countChar function below

 <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>
        function countChar(val){
                                var len = val.value.length;
                                if (len >= 500) {
                                    val.value = val.value.substring(0, 500);
                                }else {
                                    $('#charNum').text(500 - len);
                                }
        };
    </script>

In HTML call the function like

<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum">
</div>

The div will display the character count. You can do anything inside the function

Reference : Count characters in textarea

Upvotes: 1

nathanjosiah
nathanjosiah

Reputation: 4459

$('textarea').bind('keyup', function(e){
    if(e.target.value.length === 25) {
        // do stuff
    }
});

Upvotes: 0

Related Questions