jquery 输入字段模式 [英] jquery Input field pattern
问题描述
我是 JQUERY 的新手.我有一个需求,比如基于输入,需要更改相同的输入字段而不提交表单.
I am new to JQUERY. I have an requirement like based on the input, the same input field needs to be altered without submitting the form.
如果数字以 33 或 55 或 81 开头,则显示为 (xx) xxxx-xxxx,其他数字模式应为 (xxx) xxx-xxxx.
If number starts with 33 or 55 or 81, display as (xx) xxxx-xxxx, for everything other number pattern should be (xxx) xxx-xxxx.
谁能帮我解决这个问题.
Could anyone help me on this.
我试过这个代码:
<html>
<head>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>
</head>
<body>
<h1>Validation</h1>
<input id="phone" type="number">
<script>
$(document).ready(function(){
var twoNumbers = $(this).attr("phone").substr(0, 2);
if(twoNumbers == 33 || twoNumbers == 55 || twoNumbers == 81){
$("#phone").mask("(99) 9999-9999");
}else{
$("#phone").mask("(999) 999-9999");
}
});
</script>
</body>
</html>
请更正此html
推荐答案
一切都很完美,但能否请您将其附加到文本框的 keyup
事件中?它也是 $(this).val().substr(0, 2);
不是你使用的那个.请确保仅当输入为 > 时才放置掩码;2
个字符.
Everything is perfect, but can you please attach it to the keyup
event of the textbox? Also it is $(this).val().substr(0, 2);
not the one you used. Please make sure you are putting the mask only when the input is > 2
characters.
<script>
$(document).ready(function() {
$("#phone").keyup(function () {
$(this).attr("value", $(this).val());
if ($(this).val().length > 2) {
var twoNumbers = $(this).val().substr(0, 2);
if (twoNumbers == 33 || twoNumbers == 55 || twoNumbers == 81) {
console.log("First: " + twoNumbers);
$("#phone").inputmask({
mask: "(99) 9999-9999"
});
} else {
console.log("Second: " + twoNumbers);
$("#phone").inputmask({
mask: "(999) 999-9999"
});
}
}
});
});
</script>
小提琴:http://output.jsbin.com/fujunojelu
这篇关于jquery 输入字段模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!