sepehr sepehr - 3 years ago 175
HTML Question

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" />




Answer Source

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"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download