我想以占位符的形式显示电话号码的格式,而不会在用户键入该号码时被擦除。
随着用户的输入,html占位符消失。我希望占位符停留并引导用户输入电话号码。
<form action="payonline.html">
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ ">
<input type="submit" value="Submit">
</form>
答案 0 :(得分:0)
我认为您需要在javascript中使用onkeypress和onkeyup事件来创建更加用户友好的电话输入。 您可以在下面使用代码。不确定是否使用jquery,所以我使用的是纯JavaScript。
<form action="payonline.html">
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required placeholder="___ - ___ - ____ " onkeypress="validate_int(this)" onkeyup="phone_number_mask()">
<input type="submit" value="Submit">
</form>
<script>
function validate_int(myEvento) {
if ((myEvento.charCode >= 48 && myEvento.charCode <= 57) || myEvento.keyCode == 9 || myEvento.keyCode == 10 || myEvento.keyCode == 13 || myEvento.keyCode == 8 || myEvento.keyCode == 116 || myEvento.keyCode == 46 || (myEvento.keyCode <= 40 && myEvento.keyCode >= 37)) {
dato = true;
} else {
dato = false;
}
return dato;
}
function phone_number_mask() {
var myMask = "___-___-____";
var myCaja = document.getElementById("phone");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCaja.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set caret position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("phone").value = myOutPut;
document.getElementById("phone").setSelectionRange(theLastPos, theLastPos);
}
</script>