SenTaiyou
SenTaiyou

Reputation: 129

Preventing user from typing text into a text box but allowing paste keyboard shortcut

I was wondering if there was a way to disable all key-down events (such as typing text) while the text box element is selected/has focus but still allow the ctrl+v paste shortcut to be used. In other words I'd like to make it so the only way a user can enter any text into the box is by pasting it (either by using the context menu or by the ctrl+v).

Upvotes: 0

Views: 103

Answers (3)

Syed Ali Taqi
Syed Ali Taqi

Reputation: 4974

Try this simple solution:

<input type="text" id="txtbox" />


$(document).ready(function () {
    var ctrlKey = 17
    var vKey = 86
    $("#txtbox").keydown(function (e) {
        if (!(e.ctrlKey && e.which == vkey)) {
            return false;
        }
    });
});

DEMO

Upvotes: 2

SeraphimFoA
SeraphimFoA

Reputation: 466

Here's the code, deactivate keydown, but keep Ctrl+v working.

http://jsfiddle.net/70h3zron/

var ctrlActive = false;

$('#idtext').keydown(function(e) {
    if(ctrlActive)
    {
        if(event.which == 86) {
            return true;
        }
        else
        {
            e.preventDefault();
            return false;
        }
    }
    else
    {
        if(event.which == 17) 
            ctrlActive = true;
        else
        {
            e.preventDefault();
            return false;
        }
    }
});


$('#idtext').keyup(function(e) {
    if(event.which == 17) {
        ctrlActive = false;
    }
});

Upvotes: 1

VPK
VPK

Reputation: 3090

Use this in jQuery,

$('#yourTextElementId').keypress(function(){
    return false;
)};

Demo

Upvotes: 0

Related Questions