1

I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.

const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td>  <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td>  <td><input type="text" class="form-control" value="${price}" title="" ></td>  <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td>  </tr>`;

// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
 var template_add = $('#hidden-template').text();
 function render(props) {
   return function(tok, i) {
  return (i % 2) ? props[tok] : tok;
   };
 }
 var items = [  { sno: '1', optionVal: '0', price: '0' }  ];
 var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);

 $('tbody').append(items.map(function(item) {
 return dynamic_HTML.map(render(item)).join('');
 }));

});

// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
 this.value = this.value.replace(/[^0-9]/g, '');
});


$('.add-new').on('click', function () {
  $("#productTable").each(function () {

 var tr_last = $('tbody > tr:last', this).clone();
 var td_no = tr_last.find('td:first');
 var serialNumber = parseInt(td_no.text()) + 1;


 // https://stackoverflow.com/a/6588327/5081877
 var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
 var tr_first_price = parseFloat(tr_first_input.val()) || 0;
 console.dir( tr_first_price );
 
 totalamount += tr_first_price;
 $('#totalAdd').text(totalamount);

 var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
 // option:selected | .find(":selected") ~ .text(), ~.attr('value');
 var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
 console.log(' Text : ', optionText );
 console.log('Value : ', selectedValue );

 // https://stackoverflow.com/a/39065147/5081877
 $('tbody', this).append([
   { sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
 ].map(dynamic_JS).join(''));

 var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
 last_optionSel.val( selectedValue );
 
 tr_first_input.val( 0 );
 
 // https://stackoverflow.com/a/13089959/5081877
 var first_optionSel = $('#productOption');
  //$('tbody > tr:first > td:nth-child(2) > select ');
 first_optionSel.val( 0 );

    return;
  });
});


var totalamount = 0; // tr#mainRow
 $('table#productTable > tbody ').on('keyup', 'input', function(e) {
   var total =
    $(e.delegateTarget)
    .find('input')
    .map(function() {
      return parseFloat($(this).val()) || 0;
    })
    .get()
    .reduce(function(a, b) {
      return a + b;
    });
   
 $('#total').text(total);
});

<!-- Remove row - javascript & Jquery -->

$('.remove-row').on('click', function () {
 $("#productTable").each(function () {
  // added total minus deleting element price.
  $(this).closest('tr').remove();
 });
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
  <thead>
    <tr>
      <th>No.</th><th>Product</th><th>Price</th><th>Action</th>
    </tr>
  </thead>
  <tbody id="mainBody">
    
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td></td>
      <td>
      Expected Total:<span id="total">0</span><br>
      Added Total:<span id="totalAdd">0</span>
     </td>
      <td></td>
    </tr>
  </tfoot>
</table>

<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>

<script id="hidden-template" type="text/x-custom-template">
  <tr id="mainRow">
 <td>${sno}</td>
 <td>
  <select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
  <option value="0"> -- Select One --</option>
  <option value="1"> IPhone </option>
  <option value="2"> MAC </option>
  <option value="3"> Windows </option>
  </select>
 </td>
 <td>
  <input id="number_only" pattern="[0-9]" type="text" class="form-control" />
 </td>
 <td><!-- glyphicon-plus | glyphicon-remove -->
  <button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
 </td>
  </tr>
</script>
</body>

Stackoverflow snippet - using javascript onclick function remove current row is working fine.

function removeRow(onclickTAG) {
    // Iterate till we find TR tag. 
    while ( (onclickTAG = onclickTAG.parentElement)  && onclickTAG.tagName != 'TR' );
            onclickTAG.parentElement.removeChild(onclickTAG);
}

as part of jsfiddle - test and plane html file the code is not working at-least with javascript.

  1. Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
  2. I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}

Iam unable to solve it as new to jquery and its xpath element navigation.

Yash
  • 9,250
  • 2
  • 69
  • 74
  • There was issue in your code while binding issue to remove button as well as for key events. Check [here](https://jsfiddle.net/eone11bn/3/) – Developer107 Oct 09 '17 at 11:22

3 Answers3

3

There are two issues with your code:

$('table#productTable:.remove-row').on('click', function () {

here :. is an syntax error, and it is showing in console.

Second to put an event listener on dynamic html, you have to use $(document).on() like:

$(document).on('click', '.remove-row', function(){

Check the updated working fiddle here

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • first point delete function is working fine, but input fields are allowing non-numeric values. – Yash Oct 09 '17 at 11:35
0

I have added events using on click event handler as elements get added dynamically.

Have updated both events: 1. Event for remove button

$('table#productTable').on('click', '.remove-row', function() {
  //$("#productTable").each(function () {
  // added total minus deleting element price.
  $(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
  //$(element).parent().remove();
  //});
});

2. Event for input tag

$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
  $.each($('input[type=text]'), function() {
    this.value = this.value.replace(/[^0-9]/g, '');
  });
});

Refer this fiddle

Developer107
  • 1,728
  • 2
  • 14
  • 24
0

Please change $('.row).onclick like this

$('table#productTable').on('click', '.remove-row', function()

And remove this $("#productTable").each(function () {

Jinesh
  • 1,554
  • 10
  • 15