Thursday, 23 June 2011

Disable Cut, Copy, Paste etc. in a text box Thought HTML and JavaScript


function disableCtrlKeyCombination(e)
{
    var RetVal = true;
   
    //list all CTRL + key combinations you want to disable
    var forbiddenKeys = new Array('a', 'n', 'c', 'x', 'v', 'j');
    var key;
    var isCtrl;

    if(window.event)
    {
        key = window.event.keyCode;     //IE
        if(window.event.ctrlKey)
                isCtrl = true;
        else
                isCtrl = false;
    }
    else
    {
        key = e.which;     //firefox
        if(e.ctrlKey)
                isCtrl = true;
        else
                isCtrl = false;
    }

    //if ctrl is pressed check if other key is in forbidenKeys array
    if(isCtrl)
    {
        for(i=0; i<forbiddenKeys.length; i++)
        {
            //case-insensitive comparation
            if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
            {                               
                RetVal = false;
            }
        }
    }
       
    return RetVal;       
}

//Calling in HTML
<input type='text' maxlength='15' onKeyDown="JavaScript:return disableCtrlKeyCombination(event);"></input> 

No comments:

Post a Comment