0

I have two Jquery functions where one will insert a new dynamic row to a form on a button click and other function will validate the cell in that row.

var currentItem = 11;
$('#addnew').click(function(){
  currentItem++;
  $('#items').val(currentItem);
  var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control"  name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button  class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';

  $('#data').append(strToAdd);


});

Here I take the class name productSelect as the identifier for the second function to make validation. But it didn't recognize the class and the validation is not working for the rows which I add to the form by the above function.

  $('.productSelect').change(function () {

  var elementID = $(this).attr("id");
  var numberPart = elementID.split("t", 2);

  if ($(this).val() != null ) {
    $('#quantity'+ numberPart[1]).prop('required',true);
  }
});

This is how the entire code looks like

<script type='text/javascript'>

$(document).ready(function() {

$('.productSelect').change(function () {

  var elementID = $(this).attr("id");
  var numberPart = elementID.split("t", 2);

  if ($(this).val() != null ) {
    $('#quantity'+ numberPart[1]).prop('required',true);
  }
});

var currentItem = 11;
$('#addnew').click(function(){
  currentItem++;
  $('#items').val(currentItem);
  var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control"  name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button  class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';

  $('#data').append(strToAdd);


});

});

</script>
Twisty
  • 23,484
  • 1
  • 22
  • 40

1 Answers1

0

Use $(document).on.('change', '.productSelect', function (){}) Because method couldn't found the class on document ready