首页 > 解决方案 > 如何选择动态生成的行的第 n 个孩子

问题描述

onfocusout() 从动态生成的行中访问数量和价格,将它们相乘并将其分配给总数。

我的表格:

       <table id="dynamic-field" class="table table-striped table-bordered  
       dt-responsive nowrap" cellspacing="0" width="100%">
          <thead>
            <tr>
              <!-- <th> S.No </th> -->
              <th> Product Name </th>
              <th> Quantity </th>
              <th> Price </th>
              <th> Total </th>
              <th style="text-align: center;"> <i class="fa fa-plus btn 
              btn-success" id="addProduct"></i></th>
            </tr>
            <tr>
            <td style="width: 30%">
            <select id="product_id" name="product_id[]" 
            class="formcontrol" 
            required="">
            <option> --- Select ---</option>
            @foreach($products as $product)
            <option value="{{ $product->id }}"> {{ $product->name }} 
            </option>
            @endforeach
            </select>
            </td>
            <td style="width: 20%">
            <input type="number" class="form-control" id="quantity" 
            ame="quantity[]" required="">
            </td>
            <td style="width: 20%">
            <input type="number" class="form-control" id="price" 
            name="price[]" required="">
            </td>
            <td style="width: 20%">
            <input type="number" class="form-control" id="total" 
            name="total[]" required="" >
            </td>
            <td style="text-align: center;">
            <i class="fa fa-remove btn btn-danger"></i>
            </td>
            </tr>
          </thead>
          <tbody id="sales_information">

          </tbody><!-- TBODY End -->
        </table><!-- TABLE End -->

我尝试了以下代码,但这对我不起作用:

$(document).on('focusout', '#dynamic-field tr', function(e) 
  {
    var price = $(this).find('td:nth-child(1)').val();
    alert(price);
    var quantity = $(this).find('td:nth-child(2)').val();
    var result = price * quantity;
    $('#total').val(result);
  });

它在警报时显示我空白。

标签: jquery

解决方案


You can't repeat ID's in a page so change the id's on the form controls to classes and then simply target those classes.

<input type="number" class="form-control quantity" name="quantity[]" required="">

Also you are trying to target wrong nth-child() since `nth-child is not zero based like indexing is

$(document).on('focusout', '#dynamic-field tr :input', function(e) 
  {
    var price = $(this).find('.price').val();
    alert(price);
    var quantity = $(this).find('.quantity').val();
    var result = price * quantity;
    $(this).find('.total').val(result);
  });

推荐阅读