tags:

views:

117

answers:

4

i've never looped through elements with jquery and it would be great with some help.

my DOM looks like:

<div class="section">

    <div class="group">
        <div class="comment">
            <input class="comment" type="text" />
            <br />
        </div>
        <div class="link">
            <input class="link" type="text" />
            <input class="link" type="text" />
            <br />
        </div>
    </div>

    <div class="group">
        <div class="comment">
            <input class="comment" type="text" />
            <input class="comment" type="text" />
            <br />
        </div>
        <div class="link">
            <input class="link" type="text" />
            <br />
        </div>
    </div>

</div>

how do i write the code to get all values in text input fields (class=comment and class=link). there will be lot of groups with different numbers of text input fields.

thanks!

+9  A: 
$(":input.comment, :input.link").each(function() {
    alert($(this).val()); // or this.val
});

See:

karim79
val is a function, so you need parens. ()
Kyle Trauberman
Thanks Kyle, it was a speed related omission. Just fixed it,
karim79
`:input` matches any kind of input element, including select, so I figured it would be useful to include it. Of course, text inputs can be selected as `input[type=text]`, but thanks for the comment
karim79
Hmm, didn't know that. I deleted my comment when you posted the second doc link. Thanks for the info. :)
Kyle Trauberman
+3  A: 

This selects all elements with a class of comment or link, and alerts its value.

$(".comment, .link").each(function() {
    alert($(this).val());
});

Alternatively, you could select on the input type:

$("input[type='text']").each(function() {
    alert($(this).val());
});
Kyle Trauberman
Not to nitpick, but you need to lose the space between `input` and the `[type=text]` attribute filter, `input[type=text]`.
karim79
Fixed. Good eye.
Kyle Trauberman
A: 

try:

$(":input.comment, :input.link", "div.group").each(function() {
    alert($(this).val());
});
Reigel
A: 

The following syntax is clearer to me (although it's functionally equivalent to the other answers):

var elementList = $(":input.comment, :input.link");
$.each(elementList, function(i, input){
    alert($(input).val());
});
John McCollum