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
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
.
精彩评论