开发者

jQuery each function not working need to replace each attribute

开发者 https://www.devze.com 2023-02-25 11:37 出处:网络
I have this html <form method=\"POST\" action=\"\" id=\"order\" class=\"forms\"> <div> <span class=\"col1\">Ref.</span>

I have this html

<form method="POST" action="" id="order" class="forms">
    <div>
        <span class="col1">Ref.</span>
        <span class="col2">Number</span>
        <span class="col3">Color</span>
        <span class="col4">Re开发者_运维知识库marks</span>
        <span class="col5">Prijs</span>
    </div>
    <div class="order">
        <input type="text" name="ref-1" class="col1" />
        <input type="text" name="num-1" class="col2" />
        <input type="text" name="color-1" class="col3" />
        <input type="text" name="remark-1" class="col4" />
        <input type="text" name="price-1" class="col5" />
    </div>
    <a id="add" href="#">+</a>
</form>

And this jquery

$("#add").click(function() {     
    $("#order").children(":eq(1)").clone().each(function() {
            var index = $("#order").children().length - 1;
            alert(index);

        $(this).children().find(":input").each(function() {

                alert(index);

                    $(this).attr("[name]", function(i, v) {

                        return v.substr(0, v.lastIndexOf("-") + 1) + index;

                    }).val("");

                });
    }).insertBefore("#add");
});

I need to replace the -1 part of each input name to the incremented value. But the js never gets to the $(this).attr() function When I run this code it doesn't show the second alert box when I click #add


I haven't checked the whole of your code but there is a glaring error in that

.attr("[name]"

should be

.attr("name"

You also need to remove the .children() from the line

$(this).children().find(":input")

and make it

$(this).find(":input")

This is because this refers to the div element that contains the inputs. By running .children() on that it returns the input elements, and by doing find() on that it returns nothing, because find looks inside the selected elements, not-including the elements it runs on.

updated jsfiddle at http://jsfiddle.net/gaby/TpmdP/


Remove .find(":input") and pass ":input" as argument to .children(). children() can retrieve child elements even by filtering the elements.

0

精彩评论

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