gpt4 book ai didi

文本区域中的 JQuery keyup 函数

转载 作者:行者123 更新时间:2023-11-28 01:57:40 24 4
gpt4 key购买 nike

我的 HTML 中有一个字段,我想根据某些验证规则检查它的大小和值。这是 jQuery 代码:

$(function(){
$('#id_title').keyup(function() {
data = $(this).val();
if (data == " ") {
$('#output').text("The title can not be spaces");
$('#SubmitAction').attr("disabled", true);
} else {
if (data.length < 5) {
$('#output').text("The title can not be shorter than 5 characters");
$('#SubmitAction').attr("disabled", true);
} else {
if (data.length > 30) {
$('#output').text("The title can not exceed 30 characters");
$('#SubmitAction').attr("disabled", true);
}
}
}
data = $(this).val();
});
});

问题是,当它进入任何 if block 时,即使用户正确地完成了信息,它也会卡住。

最佳答案

disabled 是一个属性,要修改属性,您应该使用 prop 方法而不是 attr。您可以使用 jQuery $.trim 实用函数来检查值的长度,而不是使用空字符。

$('#id_title').keyup(function() {
var val = $.trim(this.value),
error = '';

if ( val.length === 0 ) {
error = "The title can not be empty");
} else if ( val.length < 5 || val.length > 30 ) {
error = "The title can not be shorter than 5 characters and exceed 30 characters";
}

$('#output').text(error);
$('#SubmitAction').prop("disabled", error.length);
});

请注意,在 keyup 上验证文本输入不是用户友好的,用户输入一个字符并且在第一个 keyup 事件中显示错误。我建议改用 blur 事件。

关于文本区域中的 JQuery keyup 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com