sepehr
sepehr

Reputation: 165

Unchangeable digits in textbox value in jQuery

I want to set readonly '09' digit in my input element I mean user can type in input textbox but cant edit or remove 09 in it and it is constant . The following code is only for 9 digit. Could anyone help me out with this?

$('#PhoneField').keyup(function(e) {
  if ($(this).val()[0] != '9')
    $(this).val('9' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="PhoneField" class="phoneBox" maxlength="10" />

Upvotes: 0

Views: 75

Answers (2)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

$('#PhoneField').keyup(function(e) {
  if (!$(this).val().startsWith("09","0")){
    $(this).val('09');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="text" id="PhoneField" value="09" class="phoneBox" maxlength="10" />

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 273100

you may do this :

$("#PhoneField").keydown(function(e) {
var v=$(this).val();
var f=this;
setTimeout(function () {
    if(f.value.indexOf('09') !== 0) {
        $(f).val(v);
    } 
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="PhoneField" value="09" class="phoneBox" maxlength="10"/>

Upvotes: 3

Related Questions