Jquery how to get the index of a row given only certain <tr> s, not all of them

PROBLEM: I want to get the row index of only rows where the "AC" button is. What for? because I need a dynamically added comment to match the index I get in the POST.

Here is my code:

<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<table id="items" class="table table-bordered table-hover">
    <thead>
    <tr>
        <th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
        <th width="2%">AC</th>
        <th width="15%">Codigo</th>
        <th width="38%">Articulo</th>
        <th width="15%">Precio</th>
        <th width="15%">Cantidad</th>
        <th width="15%">Total</th>

    </tr>
    </thead>
    <tbody>
    <tr>
        <td><input class="case" type="checkbox"/></td>
        <td><button class="btn btn-success addrow" type="button">AC</button></td>
        <td><input type="text" data-type="productCode" name="items[code][]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off"></td>
        <td><input type="text" data-type="productName" name="items[name][]" id="itemName_1" class="form-control autocomplete_txt" autocomplete="off"></td>
        <td><input type="number" name="items[price][]" readonly="readonly" id="price_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
        <td><input type="number" name="items[quantity][]" id="quantity_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
        <td><input type="number" name="items[total][]" readonly="readonly" id="total_1" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>

    </tr>
    </tbody>
</table>
</div>
</div>
<div class='row'>
<button class="btn btn-danger delete" type="button">-  eliminar</button>
<button class="btn btn-success addmore" type="button">+ Agregar</button>

    </div>

      

And here's the script:

var i=$('table tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><button class="btn btn-success addrow" type="button" id="addrow_'+i+'">AC</button></td>';
html += '<td><input type="text" data-type="productCode" name="items[code][]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="items[name][]" id="itemName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text"  name="items[price][]" readonly="readonly" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text"  name="items[quantity][]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text"  name="items[total][]" readonly="readonly" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '</tr>';
$('#items').append(html);
i++;
});


$(document).on("click", '.addrow', function (){
var count =  $(this).parent().parent().index();
newrow = '<tr><td><input class="case" type="checkbox"/></td><td colspan="7"><input type="text" name="items[comment]['+count+']" class="form-control"></td></tr>';
$(this).parent().parent().after(newrow); 
});

      

Here is a jsfiddle: https://jsfiddle.net/1ejw1h68/

My problem is here, I believe: var count = $ (this) .parent (). parent (). index ();

If I add new items and "THEN" adds "AC" everything works fine, I get the same indices in my POST request, but if I add an item and then a comment, etc., the indices won't match the comments.

How can I fix this?

Edit: Clarification: When I submit the form, I get a post request with an array of elements, each array has an index that matches the index of the table, my problem is that some elements may or may not have a comment.

It works if I add items and comments in order, if I add 4 items first and then add a comment to the second item, I get this in my POST:

[comment] => Array
            (
                [1] => this is a comment, and it should be index 1
            )

      

But if I, for example, add an element, then a comment, then a comment, then an element, etc., for the comment of the second element, this is what I get:

[comment] => Array
            (
                [0] => 
                [2] => this is a comment, and it should be index 1
                [4] => 
            )

      

As you can see, the second time I added comments var count = $ (this) .parent (). parent (). index (); counted comment lines in relation to the total number of indexes, how can I prevent this? or is there a better way to do this?

+3
javascript jquery html


source to share


2 answers


Here is my example that can give you an idea of ​​your problem



//To add Dynamic Row for product    
$("#add").click(function() {

  var row = $("#consumptionTable tbody>tr:last").last().clone();	    
  var oldId = Number(row.attr('id').slice(-1));	    
  var id = 1 + oldId;

  row.attr('id', 'rowformat_' + id );
  row.find('#product_' + oldId).attr('id', 'product_' + id);
  row.find('#quantity_' + oldId).attr('id', 'quantity_' + id);
  row.find('#unit_' + oldId).attr('id', 'unit_' + id);
  row.find('#errText_' + oldId).attr('id', 'errText_' + id);
  $('#consumptionTable').append(row);
  $('#quantity_' + id).val("");	//To clear value from cloned input

});
	
//To Remove the Dynamic Row
$("#remove").click(function() {	
  var rowCount = $('#consumptionTable tbody tr').length;		
  if(rowCount >1){
    $( "#consumptionTable tbody> tr:last" ).remove();
  }else{
    alert("Cannot Remove anymore Row")
  }
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8">
  <div class="form-group">
    <label for="Consumption_Detail">Consumption Detail:  
      <input type="button"  class="dynamicBtn" id="add" value="Add Row" /> 
      <input type="button"  class="dynamicBtn" id="remove" value="Remove Row" />
    </label>   
    <div class="table-responsive" >
      <table class="table table-condensed table-bordered table-hover" id="consumptionTable">
        <thead>
          <tr>										
            <th>Product <sup>*</sup></th>
            <th>Quantity <sup>*</sup></th>
            <th>Unit</th>
          </tr>
        </thead>
        <tbody id="addTbody">

          <tr id="rowformat_0">
            <td width="16%">
              <select id="product_0">
                <option value="">Select</option>
              </select>
            </td>

            <td width="4%">
              <input type="text" class="form-control"  id="quantity_0" />
            </td>

            <td width="4%">
              <select  id="unit_0" class="form-control">
                <option value="">Select</option>
              </select>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
      

Run code


0


source to share


I will answer my question because I understand that what I want to do is, in my case, the wrong way.

Why? .. Because I manually added the indexes of my comments and created another problem in this step. what would happen if the user removed the row of items above the comment? comments will no longer match items.

Here's what I did: I created dynamic comments in the item comments and hid them using "Modal Boxes" on the same line, so I solved all my problems in one step.

code:

<table id="items" class="table table-bordered table-hover">
<thead>
<tr>
    <th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
    <th width="2%" style="text-align: center">AC</th>
    <th width="15%">Codigo</th>
    <th width="38%">Articulo</th>
    <th width="15%">Precio</th>
    <th width="15%">Cantidad</th>
    <th width="15%">Total</th>

</tr>
</thead>
<tbody>
<tr>
    <td><input class="case" type="checkbox"/></td>
    <td><button class="btn btn-success" data-toggle="modal" data-target="#myModal" type="button">AC</button></td>
    <td><input type="text" data-type="productCode" name="items[code][]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off"></td>
    <td><input type="text" data-type="productName" name="items[name][]" id="itemName_1" class="form-control autocomplete_txt" autocomplete="off"></td>
    <td><input type="number" name="items[price][]" readonly="readonly" id="price_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
    <td><input type="number" name="items[quantity][]" id="quantity_1" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>
    <td>
        <input type="number" name="items[total][]" readonly="readonly" id="total_1" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
        <div id="myModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Agregar comentario</h4>
                    </div>
                    <div class="modal-body">
                        <input type="text" name="items[comment][]" class="form-control">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </td>
</tr>
</tbody>
</table>
<button class="btn btn-danger delete" type="button">- Eliminar</button>
<button class="btn btn-success addmore" type="button">+ Agregar</button>

      



Script:

var i=$('table tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><button class="btn btn-success" data-toggle="modal" data-target="#myModal_'+i+'" type="button">AC</button></td>';
html += '<td><input type="text" data-type="productCode" name="items[code][]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="items[name][]" id="itemName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text"  name="items[price][]" readonly="readonly" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text"  name="items[quantity][]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td>';
html += '<input type="text"  name="items[total][]" readonly="readonly" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">';
html += '<div id="myModal_'+i+'" class="modal fade" role="dialog">';
html += '<div class="modal-dialog">';
html += '<div class="modal-content">';
html += '<div class="modal-header">';
html += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
html += '<h4 class="modal-title">Agregar comentario</h4>';
html += '</div>';
html += '<div class="modal-body">';
html += '<input type="text" name="items[comment][]" class="form-control">';
html += '</div>';
html += '<div class="modal-footer">';
html += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
html += '</div></div></div></div>';
html += '</td>';
html += '</tr>';
$('#items').append(html);
i++;
});

      

and here is a jsfiddle: https://jsfiddle.net/fu39najg/

I hope this can help someone in the same position as me.

0


source to share







All Articles