Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Mike Perrenoud Avatar asked Jan 13 '23 11:01

Mike Perrenoud


2 Answers

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());
});
like image 151
gp. Avatar answered Jan 15 '23 00:01

gp.


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.

like image 45
Chris Hayes Avatar answered Jan 14 '23 23:01

Chris Hayes