简体   繁体   中英

Get closest input in a for loop if button click with same classes(JQuery)

I try to get the value of the closest input field (subjectId), which contanis the id, in other input. But it always takes the last subjectId.

The HTML-Code:

@foreach($grades As $grade)
<tr class="subjectGrades">
    <td class="min-td-size">
    <button class="btn btn-default btn-sm pull-left min-margin-right" class="overviewShowSubjectGrades" data-toggle="modal" data-target="#modalShowGrades">Show Grades</button>                              
    <button class="btn btn-default btn-sm pull-left" class="overviewAddGrade" data-toggle="modal" data-target="#modalAddGrade">+</button>
    <input type="hidden" class="subjectId" value="{!! $grade->subjectId !!}">
    </td>                        
</tr>
@endforeach

The JQuery-Code:

$('.overviewAddGrade').click(function () {
        var subjectId = $(this).closest('.subjectId').val();    
        $('#modalSubjectId').val() = subjectId;    
   });

Missing a . in your class selector for subjectId , but the problem is closest searches up the DOM tree - while your element is a sibling. You can use closest to get the parent, then find to get the target elem:

var subjectId = $(this).closest("td").find('.subjectId').val();                  

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