<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 8 年前。
标签 javascript jquery html css
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 8 年前。
我最近问了一个关于在检查非空文本区域时如何向文本区域添加彩色边框的问题。我现在发现我的代码只检查 1 个填充的文本区域,然后它会验证表单。
我如何编辑以下代码以确保它检查每个文本区域,以便所有文本区域都需要输入。
function validate() {
var success = true;
var inputarea = $('#input-area textarea');
for(i = 0; i < inputarea.length; i++)
{
if(inputarea.val() === "")
{
console.log("Missing textarea input");
$('#input-area textarea').fadeIn().html('').css("border","1px solid red");
success = false;
}
}
return success;
}
其他一切都按照我想要的方式工作,我只需要确保它检查所有文本区域的输入,而不仅仅是 1 个文本区域作为输入。
最佳答案
这是一个带有相应 jsFiddle 的备用代码片段。
在 HTML 中我们有两个文本区域。
Area 1
<textarea rows="4"></textarea>
<br/>
Area 2
<textarea rows="4"></textarea>
<br/>
<button>Validate</button>
这里是逻辑的核心:
function validate() {
var valid = true;
$("textarea").each(function(index, element) {
if (valid == true) {
valid = $(element).val().length > 0;
}
});
return valid;
}
$("button").click(function() {
alert("Valid = " + validate());
});
有一个名为 validate() 的函数,仅当页面上的所有文本区域都有内容时才返回 true,否则返回 false。单击该按钮时,将调用验证函数并将结果显示在警告框中。希望代码是不言自明的,但如果不是,请根据其引用检查每个相应的 jQuery 方法。如果还有不明之处,请回复评论,我会尽力详细说明。
关于javascript - 如何检查多个文本区域的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26580658/