Sri
Sri

Reputation: 1505

Control+backspace in textbox javascript

I have a requirement of having a text-box with default value say "PF_". If I type something and press control+backspace All the values are been deleted. This problem occurs only If I have an underscore "_" at the end.

Javascript

var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function (event) {
    var $field = $(this);
    $('#output').text(event.which + '-' + this.selectionStart);
    if ((event.which != 37 && (event.which != 39)) && ((this.selectionStart < readOnlyLength) || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
        return false;
    }
});

Html

<input id="field" type="text" value="PF_" size="50" />

I have tried a sample fiddle.

Any Idea?

Upvotes: 1

Views: 730

Answers (2)

user156213
user156213

Reputation: 766

I'm not sure if this is what you're after, but this will reset the field to the previous value if the user tries to modify the read-only part:

$('#field').on('keypress, keydown', function (event) {
    var $field = $(this);
    var old = $field.val();
    setTimeout(function(){
        if($field.val().slice(0,3)!='PF_') {
            $field.val(old);
        }
    },0);
});

Edit: in response to op's comments, try this code instead:

$('#field').on('keypress, keydown', function (event) {
    var $field = $(this);
    if(event.ctrlKey && event.which==8) { // ctrl-backspace
        $field.val('PF_');
        return false;
    }
    var old = $field.val();
    setTimeout(function(){
        if($field.val().slice(0,3)!='PF_') {
            $field.val(old);
        }
    },0);
});

Fiddle

Upvotes: 1

Ahs N
Ahs N

Reputation: 8366

This is how I would do it:

$("#field").keyup(function(e){
    if($(this).val().length < 3){
        $(this).val("PF_");
    }
});

Here is the JSFiddle demo

Upvotes: 0

Related Questions