Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through elements with jquery?

Tags:

jquery

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!

like image 952
ajsie Avatar asked Jan 24 '10 16:01

ajsie


3 Answers

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

See:

  • http://docs.jquery.com/Utilities/jQuery.each
  • http://docs.jquery.com/Selectors/input
like image 97
karim79 Avatar answered Oct 15 '22 12:10

karim79


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());
});
like image 23
Kyle Trauberman Avatar answered Oct 15 '22 13:10

Kyle Trauberman


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());
});
like image 44
John McCollum Avatar answered Oct 15 '22 11:10

John McCollum