不允许用户从输入中删除特定字符

时间:2017-02-08 12:58:14

标签: javascript

我正在尝试使用国家/地区代码输入电话号码。我默认放置+,但它是可移动的。如何使其无法移除,以便用户无法从输入中删除+



document.getElementById("phonenumber").onkeypress = function(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode == 13) return true;
  if ((charCode > 31) && (charCode < 48 || charCode > 57)) {
    document.getElementById("phonenumber").style.backgroundColor = "rgba(255,0,0,0.5)";
    document.getElementById("lblphonenumber").innerHTML = "Phone number is invalid";
    return false;
  } else {
    document.getElementById("phonenumber").style.backgroundColor = "white";
    document.getElementById("lblphonenumber").innerHTML = "Phone number is valid";
    return true;
  }
}
&#13;
<label id="lblphonenumber" for="phonenumber" class="form-field-label">Please enter your phone number with country code</label>
<br/>
<input type="text" id="phonenumber" name="phonenumber" value="+" size="20">
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

通过这种方式你可以做到。

&#13;
&#13;
document.getElementById("phonenumber").onkeypress = function(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (charCode == 13) return true;
  if ((charCode > 31) && (charCode < 48 || charCode > 57)) {
    document.getElementById("phonenumber").style.backgroundColor = "rgba(255,0,0,0.5)";
    document.getElementById("lblphonenumber").innerHTML = "Phone number is invalid";
    return false;
  } else {
    document.getElementById("phonenumber").style.backgroundColor = "white";
    document.getElementById("lblphonenumber").innerHTML = "Phone number is valid";
    return true;
  }
}
&#13;
<style>
  label {
    position: relative;
  }
  label::after {
    content: "+";
    display: block;
    position: absolute;
    left: 4px;
    top: 20px;
    font-size: 14px;
  }
  input {
    padding-left: 12px;
  }
</style>
<label id="lblphonenumber" for="phonenumber" class="form-field-label">Please enter your phone number with country code</label>
<br/>
<input type="text" id="phonenumber" name="phonenumber" value="" size="20">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用CSS轻松完成此操作。

但是如果你想用javascript做这个,你可以试试这样的东西..

    $("input").keydown(function(e) {
   var pv=$(this).val();
   var field=this;
   setTimeout(function () {
    if(field.value.indexOf('+') !== 0) {
        $(field).val(pv);
    } 
}, 1);
 });