[英]validating multiple inputs at the same time
我有三個文本輸入:
在表格中,我只有以下輸入類型:文本。
我希望每個字符至少要有4個字符長,所以我決定一起驗證它們。
我想使用Jquery來顯示一條錯誤消息,當長度小於4時為紅色,而當長度大於4時為綠色。 我分別用以下ID放置了三個錯誤消息:
(第一個字母對應於input,示例名字:flength等)
所以這是我的代碼來做到這一點:
$('input [type= text]').keyup(function ({
var l = $(this).val();
var x = l.id;
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
為什么該腳本不起作用? 我應該修改什么?
編輯
演示
看到您的評論后
更改var x = $(this).attr("id");
也不會解決問題
因為$(this).attr("id")
給出了您當前的元素ID,而您當前的元素是您的輸入標簽元素,並且您沒有設置id
屬性,而是將其設置為div
標簽,就像您在注釋中提到的那樣,因為您嘗試檢索尚未設置的id屬性,並且收到錯誤消息。
我可以給出的一種解決方案是這種方式
<input type="text" name="flength"/> // set name attribute same as div ids
<input type="text" name="llength"/>
<input type="text" name="ulength"/>
$('input[type=text]').keyup(function ({
var l = $(this).val(); // get the input string
var x = $(this).attr('name'); // get the current input element name attribute
if (l.length < 4) {
$('#' + x).removeClass('valid').addClass('invalid');
} else {
$('#' + x).removeClass('invalid').addClass('valid');
}
});
嘗試這個
$(document).ready(function () {
$('input[type=text]').keyup(function () {
var l = $(this).val();
var x = $(this).attr('id'); // notice it is not l.id
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
});
嘗試更改var x = l.id;
寬度var x = $(this).id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.