yigitozmen
yigitozmen

Reputation: 957

get item from multiple inputs with jquery which have the same name

I am listing items via table then want to change individual names of items.

<td class="tdFileName">
    <?php $nameArray = explode(".", $f->file_name); ?>
    <input type="text" name="ra_name" class="raName" value="{{$nameArray[0]}}">
    <button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
<td>{{$userName}}</td>
 $('.btnRaName').on('click', function (e) {
    e.preventDefault();
    alert($('.raName').val());
    location.reload();
});

When I click the individual button I only get first input's value. How can I fix that?

Upvotes: 1

Views: 127

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

Select the element relative to your clicked element using sibling()

$('.btnRaName').on('click', function (e) {
        e.preventDefault();
        var raName = $(this).siblings('.raName').val(); 
        console.log(raName);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<td class="tdFileName">
    <input type="text" name="ra_name" class="raName" value="the value">
    <button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
<td class="tdFileName">
    <input type="text" name="ra_name" class="raName" value="another value">
    <button type="submit" class="btn-warning btnRaName">Düzenle</button>
</td>
  </table>

Upvotes: 0

void
void

Reputation: 36703

On click you need to pick the prev HTML element as it will be the desired input field:

$('.btnRaName').on('click', function (e) {
    e.preventDefault();
    var txt = $(this).prev('input.raName').val();
    console.log(txt);
    location.reload();
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to use DOM traversal to get only the .raName element thats related to the clicked button. Try this:

$('.btnRaName').on('click', function (e) {
    e.preventDefault();
    var raName = $(this).closest('td').find('.raName').val(); 
    console.log(raName);
});

Upvotes: 1

Related Questions