繁体   English   中英

用户的文本输入-移动前缀应限制输入的数字量。

[英]user's text input - mobile prefix should limit the amount of digits being entered.

IMG 我输入了移动前缀和数字:

  <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));
        }
    }); 
    }());

JSFIDDLE链接

您可以使用以下代码段实现您的目的。 .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM