简体   繁体   中英

jQuery get value closest input field

I have HTML code like this:

<tr>
  <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td>
  <td class='comm'><input class='narrow' value='' size='5'/></td>
</tr>

This code will be auto generated by a JS function, so it happens more often. to get the Value from the first input I use this function:

jQuery('#tbl_order .qty input').bind('change', function() {

Within this function I want to get the next input value. I have tried this what does not work

jQuery(this).closest(".comm input").val()

.closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

You can use find() on the closest tr element. I will also prefer using on() and input event instead of bind() and change respectively.

Demo:

 jQuery('#tbl_order .qty input').on('input', function() { var nextVal = jQuery(this).closest("tr").find(".comm input").val(); console.log(nextVal); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr id="tbl_order"> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> <td class='comm'><input class='narrow' value='1234' size='5'/></td> </tr> </table>

You can use next() combines with closest()

 $('#tbl_order .qty input').bind('change', function() { var $currentTd = $(this).closest("td"); var $nextTd = $currentTd.next(); var value = $nextTd.find("input").val(); console.log(value); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tbl_order"> <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> <td class='comm'><input class='narrow' value='' size='5'/></td> </tr> </table>

 $('.fa fa-trash').on('click', function () { 
 $tr = $(this).closest('tr');
    var data = $tr.children('td').map(function () {
      return $(this).text();
    }).get();
    console.log(data);


<table id="tbl_order">
<tr>
<td><input class='narrow' value='1' /><i class='fa fa-trash' aria- 
hidden='true'></i></td>
<td><input class='narrow' value='' size='5'/></td>
</tr>
</table>

this may give you some idea about mapping function. here I give jquery onclick class to fa fa-trash. so whenever the event is fired the particular row get selected. (i hope in the table your getting data from backend code)

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