2016-08-17 123 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>