void
void

Reputation: 36703

Disabling BACKSPACE in chrome

I have an input field for mobile numbers and i want that inside that input field "+91" should be visible to the user all the time.. means he can not erase it.

So i planned to disable BACKSPACE and DELETE button when the value of INPUT FIELD is equal to +91

The startegy is working fine for me in FIREFOX but its all screwed up in CHROME.

I googled a lot but couldnt find any successfull code for Disabling Backspace in CHROME. :(

Here is my code for FIREFOX

<script  language="JavaScript" type="text/javascript">
document.onkeypress = function(e)  // FireFox/Others 
    {
    var t=e.target.id;
    var kc=e.keyCode;
    if ((kc == 8 || kc == 46) && t == "phonen" && document.getElementById(t).value=="+91")
    { e.preventDefault();
        return false;}
    else {
                return true

    }
   }
   function sett(e)
   {e.value="+91";}
</script>

Can anyone suggest me how can i do the same in CHROME???

Upvotes: 0

Views: 854

Answers (4)

Nono
Nono

Reputation: 7302

Try this with jQuery:

// HTML Code

<input type="text" name="phone" id="phone" class='phone' placeholder='+918888888888' value='' maxlength='13' />

// jQuery code

$(document).keydown(function (e) {
    var l = $('.phone').val().length;
    var elid = $(document.activeElement).hasClass('phone');
    if (e.keyCode === 8 && elid && l == 3) {
        return false;
    } else {
        return true;
    }
});

Fiddle DEMO

Upvotes: 0

Yoshi
Yoshi

Reputation: 54659

As I wrote in a comment... Don't even bother with this kind of approach. Just fake it. Here's a simple way (though you might want to adjust fonts, spacing, etc.):

html:

<div class="prefix-wrapper">
  <span class="prefix">+91</span>
  <input type="text" value="">
</div>

css:

.prefix-wrapper {
  position: relative;
}

.prefix-wrapper .prefix {
  position: absolute;
  z-index: 2;
  top: 3px;
  left: 5px;
  color: #999;
}

input {
  padding-left: 30px;
}

demo: http://jsbin.com/elatot/1/

Upvotes: 3

Ren&#233; Wolferink
Ren&#233; Wolferink

Reputation: 3548

A solution not using jQuery would be to hook up to the change/keyup events directly:

var checkPhone = function (e) {
    if (e.target.value.indexOf('+91') != 0) {
        e.target.value = '+91';
    }
}
var phoneElement = document.getElementById('phonen');
phoneElement.onchange = checkPhone;
phoneElement.onkeyup = checkPhone;

Upvotes: 0

lukas.pukenis
lukas.pukenis

Reputation: 13597

User still can click with a mouse or move the cursor and edit +91 strings.

I would suggest that you bind .keyup and .change handlers to your input and check then if it contains your prefix(note that jQuery would be it much easier). Like this:

$('#your_input_id').on('keyup change', function() {
  if ( $(this).val().indexof('+91') != 0) $(this).val('+91');
});

Upvotes: 0

Related Questions