Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Setting the value of multiple inputs with the same id using jQuery?

Considering the following HTML:

<form id="upvoteForm" method="post" action="/post/upvote">
    <input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
    <input type="text" name="post_id" id="post_id"/>
</form>

<input type="hidden" id="_postid" value="1"/>

I'm trying to set the two input fields with the name post_id to to value from _postid using this JavaScript and jQuery:

$(document).ready(function() {
    $('#post_id').val($('#_postid').val());
});

However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.

Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have button inputs that I've styled the way I want but then I use the onclick to call the submit of the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.

Upvotes: 4

Views: 25785

Answers (2)

gp.
gp.

Reputation: 8225

id is always unique. you cannot select 2 elements with same id. select by name

$(document).ready(function() {
    $('input[name=post_id]').val($('#_postid').val());
});

Upvotes: 9

Chris Hayes
Chris Hayes

Reputation: 12040

Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an input inside of a form with the name attribute set to post_id.

Upvotes: 2

Related Questions