开发者

Having multiple identical IDs in a loop and using jQuery with them

I hav开发者_开发百科e a loop that generates a bunch of these:

<textarea id="uar"></textarea>

The same loop generates a submit link next to each textarea.

That link will post this form:

<form action="php/unApprovePost.php" method="POST" id="unApprovePost">
   <input type="hidden" id="uaid" name="uaid"/>
   <input type="hidden" id="uadc" name="uadc"/>
</form>

I populate #uaid successfully, but when I try to populate #uadc, only the first iteration of the loop has functionality. What I mean is - only the first textarea will properly post what I want. If I try using any textareas other than the first one, they don't submit anything. I think it has something to do with the uniqueness of IDs in HTML. I tried using a class .uar but that doesn't really work either - same behavior. Any help?

Here's my jQuery code:

    $('#unApprovePost').submit(function() {
        $('#uadc').val($('#uar').val());
    });

Edit: There is a dynamic amount of loop iterations, so I can't really have something like class="uar1". I tried making it class .uar for the textareas and using this jQuery code:

$('#unApprovePost').submit(function() {
   $('#uadc').val($('.uar').val());
});

But the problem persists.


You can't have multiple HTML elements with the same id. It is just plain wrong and it can leads to some weird behavior in your pages. It is totally normal that only the first textarea works, because jQuery will look for the given id, find the first, and send the form.

It is the same problem when you're using always the same class, jQuery find the first one and send the form.

I suggest you use a different class for each textarea instead (ie uar1, uar2, uar3, etc)


An ID is supposed to be unique on the page. jQuery/javascript only expects one element to be present when referred to by an ID.

Use either class or name to loop the elements, whichever fits your need.


$('#uadc') returns the element with ID uadc. If you have multiple elements with that ID, it won't work.

<input name="uadc"/> will submit its value to the server using key uadc. If you have multiple inputs with the same name in the same form, it won't work.


If you wrap each of the id's and submits in their own form it should work. This would allow each submit to send the correct text area based on the selected submit.

<form action="php/unApprovePost.php" method="POST" id="unApprovePost">
    <input type="hidden" id="uaid" name="uaid"/>
    <input type="hidden" id="uadc" name="uadc"/>
    <input type="submit" id="submit" name="submit"/>
</form>

Otherwise you could manually build up a list of all id's if you truly wanted and send a list in. This might look something like:

var values = []
$.each($('#uaid'), function(i, item){
    values.append($(item).val());
}

The result would be a values array that you could then manually post to the page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜