[英]user's text input - mobile prefix should limit the amount of digits being entered.
<div class="two columns">
<input class="sgprefix" id="mobileprefix" name="mobileprefix" type="text">
</div>
<div class="nine columns">
<input id="mobile" name="mobile" type="text" class="input numeric-only">
</div>
我要实现的目标是-如果用户在移动电话前缀中输入值65,则它将移动电话号码限制为8位数字。
我不想使用maxlength,因为它将永远限制为8
您可以尝试以下代码:
$('#mobile').keyup(function(){
var count=$('#mobileprefix').val();
if(count=="65"){
$(this).attr('maxlength','8');
}
else{
$(this).attr('maxlength','10'); }
});
如果要删除maxlength
属性,请使用以下代码:
$(this).removeAttr('maxlength');
编辑:检查下面的代码,如果您更改#mobileprefix
的值, #mobileprefix
相应地更改。
(function(){
$('#mobile').keyup(function(){
var count=$('#mobileprefix').val();
if(count=="65"){
$(this).attr('maxlength','8');
}
else{
$(this).removeAttr('maxlength'); }
});
$('#mobileprefix').keyup(function(){
if($(this).val()=="65"){
$('#mobile').val($('#mobile').val().substring(0,8));
}
});
}());
您可以使用以下代码段实现您的目的。 .sgprefix
值更改时,请检查是否为65
,为number字段设置maxlength
属性,否则删除maxlength
属性。
$(document).ready(function() { $('.sgprefix').change( function() { if ($(this).val() == 65) { $('#mobile').attr('maxlength', 8); } else { $('#mobile').removeAttr('maxlength'); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="two columns"> <input class="sgprefix" id="mobileprefix" name="mobileprefix" type="text"> </div> <div class="nine columns"> <input id="mobile" name="mobile" type="text" class="input numeric-only"> </div>
您可以使用javascript实现。 您可以在mobileprefix上注册一个keyup事件。 当执行加键动作时,检查值的长度,如果值为2,则将maxLength设置为6,否则将其设置为8。如果用户仅加1位数字,则可能要添加一些动作;如果确实添加了数字。
document.getElementById("mobileprefix").onkeyup = function() { if (document.getElementById("mobileprefix").value == '65') { document.getElementById("mobile").setAttribute("maxLength", 8); } else { document.getElementById("mobile").removeAttribute("maxLength"); } };
<div class="two columns"> <input class="sgprefix" id="mobileprefix" name="mobileprefix" type="text"> </div> <div class="nine columns"> <input id="mobile" name="mobile" type="text" class="input numeric-only"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.