[英]Limit number of characters in input fields without editing HTML
我正在使用此插件在 WordPress 網站上建立人員數據庫。 我想限制用戶可以在注冊表單中的某些字段( textarea
和input type="text"
)中input type="text"
的字符數。 由於我使用的是插件,我無法編輯頁面的 HTML,所以我不能只使用maxlength
屬性。
如何限制用戶可以輸入的字符數 - 最好還顯示剩余字符數 - 無需訪問 HTML? 你能告訴我要編輯哪些文件,使用什么代碼以及把它放在哪里嗎?
您可以使用 jQuery 設置最大長度以及追加:剩余字符數
$("input").each(function() {
var $this = $(this);
var maxLength = 50;
$this.attr('maxlength', maxLength);
var el = $("<span class=\"character-count\">" + maxLength + "</span>");
el.insertAfter($this);
$this.bind('keyup', function() {
var cc = $this.val().length;
el.text(maxLength - cc);
});
});
您只需要通過更改第一行的"input"
以及根據每個允許的最大字符數更改maxLength
變量來指定要將函數應用於哪個輸入。 您也可以修改此函數以接收多個字段的參數。
這是一個修改后的版本,可讓您將其應用於多個輸入:
使用 MagJS 很容易做到這一點。
這是一個完整的工作示例:
HTML :
<div id="limit">
<h2>Characters left: <length/></h2>
<input>
<textarea></textarea>
</div>
JS:
var demo = {}
demo.view = function(state, props) {
state.textarea = state.input = {
_oninput: function() {
state.length = props.limit - this.value.length;
if (this.value.length > props.limit) {
alert('max length reached:' + props.limit)
this.value = this.value.substr(0, props.limit)
}
}
}
}
var props = {
limit: 10,
}
mag.module("limit", demo, props)
這是工作示例的鏈接: http : //jsbin.com/sabefizuxi/edit?html,js,output
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.