2016-08-17 122 views
0

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个位数。

我不希望使用最大长度为将其限定为8永远

+0

而且它是一个绝对鉴于手机号码不能与65 _after_前缀开始? – CBroe

+0

我不是我按照你的问题 - \t 我只想检查用户是否输入了数值65,然后它将手机号码数字限制为8位数, –

+0

我在问,如果用户的手机号码以65开始前缀 - 即,他们的号码将是6565 ... - 在这种情况下,将数字位数限制为8是否有意义? – CBroe

回答

2

你可以试试这个代码:如果你想删除maxlength属性使用此代码

$('#mobile').keyup(function(){  
var count=$('#mobileprefix').val(); 
     if(count=="65"){ 
      $(this).attr('maxlength','8'); 
     } 
    else{ 
     $(this).attr('maxlength','10'); } 
}); 

$(this).removeAttr('maxlength'); 

编辑:检查下面的代码,它会相应地改变,如果你改变#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 LINK

0

你可以achive与JavaScript的。您可以在您的移动前缀上注册一个关键事件。执行键控动作时,检查值的长度,如果它是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>

+0

我只想检查用户是否输入了数值65,然后将手机号码数字限制为8位,我也更喜欢使用sgprefix类,以便将其应用于不同的前缀字段 –

1

您可以使用下面的代码,以满足您的目的。当.sgprefix的值更改时,如果是,请检查它是否为65,否则请设置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>