本文介绍了为什么.val()不是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态表单,用户提供名称和说明:

I have a dynamic form where the user provides a name and description:

<label>Name</label><br />
<input type="text" name="name[]" maxlength="255" /><br />

<label>Description</label><br />
<textarea name="desc[]"></textarea><br />

我正在尝试使用Javascript验证表单,以确保如果指定了名称,那么说明必须输入。

I am trying to validate the form with Javascript to ensure that if the name is specified, then a description must be entered.

$("input[name='name[]']").each(function() {
    var index = $("input[name='name[]']").index(this);
    if ($(this).val() != '') {
        alert($("textarea[name='desc[]']").get(index).value);
        alert($("textarea[name='desc[]']").get(index).val());
    }
}

第一个alert()按预期工作但是我得到的第二个警告:
$(textarea [name ='desc []'])。get(index).val()不是函数

The first alert() works as expected however with the second alert I get:$("textarea[name='desc[]']").get(index).val() is not a function

有什么区别?为什么我不能使用jQuery函数?

What is the difference? Why can't I use the jQuery function?

推荐答案

使用而不是和它w返回一个jQuery对象.jQuery对象将有一个val()方法,该方法应该按照textarea的预期工作。

Use eq(index) instead of get(index) and it will return a jQuery object. The jQuery object will have a val() method that should work as expected for a textarea.

示例:

$("input[name='name[]']").each(function() {
    var index = $("input[name='name[]']").index(this);
    if ($(this).val() != '') {
        alert($("textarea[name='desc[]']").eq(index).val());
    }
});

这篇关于为什么.val()不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:54
查看更多