Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  117] [ 3]  / answers: 1 / hits: 37940  / 15 Years ago, fri, september 25, 2009, 12:00:00

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?


More From » jquery

 Answers
9

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.



val() documentation




A value is returned for all input
elements, including selects and
textareas. For multiple selects an
array of values is returned.




Example:



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

[#98618] Monday, September 21, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;