1

I want to bind a function to all the textarea and want to run it whenever a key gets pressed.

function fx(docid)
{
  $('#'+docid).val=encodeURIComponent($('#'+docid).val());
  //document.getElementByID('docid').value = encodeURIComponent(document.getElementByID('docid').value);
}

Note: the page will have different textarea, I want a single function to do the same job for all the textarea. I don't want to hard code the event with the textarea <textarea onkeydown="..." />

Edit
I want to trigger the function on multiple events, thats on keypress, keydown,click

2 Answers 2

3

Just pass in textarea as the selector. If you want it to trigger for text inputs as well then use textarea, input[type="text"] for the selector:

var fxHandler = function (e) {
    var yourDocId;
    // code to find/set yourDocId
    fx( yourDocId );
};

// bind to whatever events you need
$('textarea').bind('keydown', fxHandler)
             .bind('keyup', fxHandler)
             .bind('click', fxHandler);

Of course, if you run your function as written it will double, triply, etc encode the value, so you'll need to write a function that leaves %## values alone.

Sign up to request clarification or add additional context in comments.

Comments

1

Similar to @mVChr's answer,

$('textarea').bind('keypress keydown click', function (e) {
    var $this = $(this);
    $this.val(encodeURIComponent($this.val()));
});

but you almost certainly don't want to run the exact same function on keypress and on keydown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.