简体   繁体   中英

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?

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

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

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> 

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