Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .val() not a function?

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 />

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());
    }
}

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

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

like image 842
Matt McCormick Avatar asked Sep 25 '09 21:09

Matt McCormick


1 Answers

Because

$("textarea[name='desc[]']").get(index);

is DOM object, not jquery. It has not method val. Use

$("textarea[name='desc[]']:eq(" + index + ")").val();

for textarea value.

like image 123
Anatoliy Avatar answered Sep 21 '22 13:09

Anatoliy