简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM