开发者

Bind a function to all text input - jQuery

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 f开发者_开发知识库unction on multiple events, thats on keypress, keydown,click


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜