4

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.

1
  • 1
    The id attribute is always supposed to be unique. Commented Sep 3, 2013 at 1:33

2 Answers 2

9

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());
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.