2016-04-19 28 views

回答

3
<input type="text" name="fieldname" maxlength="10"> 

您可以使用maxlenght屬性來禁止輸入比預期更多的字符。你不需要JS。

如果你還是想用JS的話:

$("#myformid").keypress(function() { 
    if($(this).val().length > 10) { 
     //display your warinig the way you chose 
    } 
] 
}); 
+0

我已經這樣做了,但是如果用戶試圖輸入更多的信息,我們想要彈出一個錯誤消息 – discodowney

+0

然後你需要javascript。那裏有無數的驗證庫。 – dmoo

+1

@discodowney添加了js代碼來檢測輸入了多少個字符。我不知道,你想怎麼顯示你警告你,所以我把這部分留空 –

1

相信這是可能的! 首先,計算輸入的字符,然後打印出你想要的信息(這裏是:「剩下的字符:X」,在我的例子中最大長度爲100)。

這是JSFiddle


HTML:

<textarea rows="4" cols="50" id ="yourtextarea"> 
</textarea> 

<div id="info"></div> 

JS:

$("#yourtextarea").keyup(function(){ 
    $("#info").text("Characters left: " + (100 - $(this).val().length)); 
    }); 
0
function check_length(my_form) 
{ 
    maxLen = 50; // max number of characters allowed 
    if (my_form.my_text.value.length >= maxLen) { 
    var msg = "You have reached your maximum limit of characters allowed"; 
    alert(msg); 
    my_form.my_text.value = my_form.my_text.value.substring(0, maxLen); 
    } 
} 


<textarea onKeyPress=check_length(this.form); onKeyDown=check_length(this.form); name=my_text rows=4 cols=30></textarea> 
0

下面就來驗證用戶輸入,而無需使用Jquery的代碼。

<textarea id=txt onKeyUp=check() maxlength=10> 
Abc 
</textarea> 
<div id=warning></div> 

<script> 
function check() { 
    stringLength = document.getElementById('txt').value.length; 
    if (stringLength >= 10) { 
     document.getElementById('warning').innerText = "Maximum characters are 10" 
    } else { 
     document.getElementById('warning').innerText = "" 
    } 
} 
</script>