Cavid Nasirov Cavid Nasirov - 1 year ago 82
Javascript Question

getting input value in ajax from table - spring mvc

I want to get input in ajax in which row edit button is clicked.But i always get input which in first row.
This is my html code:

<table class="table table-striped" id = "cardTable">
<th>edit card</th>

<c:forEach var="card" items="${cards}">

<td>${} <input id="card" name="card" type="hidden" value="${ }"></td>

<!--<td><button data-toggle="modal" data-target="#cardUpdate" class="btn btn-primary">Edit</Button></td>-->
<td><button onclick="addAttribute()" class="btn-primary">edit</button></td>


This is my ajax code:

function addAttribute() {
var card = $('#card').closest("tr").parent('td').find('input[name=name]').val();
url: contexPath + "/getUpdatableCard",
data:"card=" + card,
contentType : "application/json",
success:function(data) {
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);


Can anyone help me please?

Answer Source

You have multiple elements like this:

<input id="card" ...

Repeating an id is invalid HTML, so the behavior of this is technically undefined:


This may be browser-specific, but what appears to be happening here is that it's matching the first element with that id. You'd need to use valid HTML and adjust the selector accordingly to match all of them. Something like this:

<input class="card" ...



However, this isn't entirely necessary in the first place. Because when you click your button, you only want the input relative to that button, so you don't want to select all of the input elements anyway. (And even if you did, as soon as you called .val() you'd still resolve only to the first in the matched set.)

Essentially, I think you want something like this:

var card = $(this).closest('tr').find('input[name=name]').val();

That is, starting from this you traverse to the containing <tr> and then find the input[name=name] therein. (Though I'm not seeing an input[name=name] in your code in the first place. A typo perhaps?)