开发者

loop through elements with 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!


$(":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


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


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


Answering to the question.

First line for onload: We need to loop through using each loop. Second Line for looping the text fields, suppose you need loop a different input type - just replace with that Third line - Ensuring it is not blank Fourth line - will be your business logic (In this case, im trying to parse the input text field.)

See this fiddle: http://jsfiddle.net/5FVtR/86/

$( document ).ready(function() {
    $(":text").each(function() {
        if($(this).val() !='') {
            $(this).val()=parseFloat($(this).val()).toFixed(2)
            return false;
        }
    });


try:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜