1

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?

4
  • Try keypress keydown instead of keypress, keydown. Commented Aug 14, 2015 at 6:57
  • Same result @RejithRKrishnan Commented Aug 14, 2015 at 7:01
  • Same result with space char. Commented Aug 14, 2015 at 7:03
  • Only with underscore '_' at the End deletes all the texts. Does not work with keypress keydown Commented Aug 14, 2015 at 7:07

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice one. But This is not I was looking for. I dont want the previous value when control+bkspce. The values should be deleted.
Edited my answer; is the new fiddle what you want?: jsfiddle.net/2hx7dak0/18
0

This is how I would do it:

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

Here is the JSFiddle demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.