0

I am facing an issue i want to add the jquery validation on dynamically generated input fields. I am not getting how can i apply this for all the dynamically generated input fields.

Here is my code :

<div class="inventory_table_main">
            <!-- start: TEXT AREA PANEL -->
            <div class="panel panel-white">
                <div class="panel-heading">
                    <h4 class="panel-title">Text <span class="text-bold">Area</span></h4>
                </div>
                <div class="panel-body">

                    <!--    <form action="" method="POST">  -->
                    <?php $data = array(
                        'id'=>'inventory_form', 
                        ); ?>
                    <?php  echo form_open('main/store',$data); ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="inv_tbl">
                            <thead>
                                <th>No</th>
                                <th>Product Name</th>
                                <th>Quantity</th>
                                <th>Price</th>
                                <th>Discount</th>
                                <th>Amount</th>
                                <th><input type="button" value="+" id="add" class="btn btn-primary"></th>
                            </thead>
                            <tbody class="detail">
                                <tr>
                                    <td class="no">1</td>
                                    <td><input type="text" class="form-control productname" name="productname[]" id="productname"></td>
                                    <td><input type="text" class="form-control quantity" name="quantity[]"></td>
                                    <td><input type="text" class="form-control price" name="price[]"></td>
                                    <td><input type="text" class="form-control discount" name="discount[]"></td>
                                    <td><input type="text" class="form-control amount" name="amount[]"></td>
                                    <td><a href="#" class="remove">Delete</a></td>  

                            </tr>  
                        </tbody>  
                        <tfoot>  
                        <th></th>  
                        <th></th>  
                        <th></th>  
                        <th></th>  
                        <th class="text-center"><button class="btn btn-success" id="save_btn" type="submit" name="sale_submit_btn">Save</button></th>  
                        <th style="text-align:center;" class="total">0<b></b></th> 

                        </tfoot>  

                        </table>

                        </div> 
                        <?php echo form_close(); ?>
<!--</form>-->


                        </div>
                    </div> 
        </div>

code for jquery:

// All custom javascript code goes here


$(function() {
    $('#add').click(function() {
        addnewrow();
    });
    $('body').delegate('.remove', 'click', function(event) {
        $(this).parent().parent().remove();
        update_tbl();
        event.preventDefault();

    });
    $('body').delegate('.quantity,.price,.discount', 'keyup', function() {
        var tr = $(this).parent().parent();

        var qty = tr.find('.quantity').val();
        var price = tr.find('.price').val();

        var dis = tr.find('.discount').val();
        var amt = (qty * price) - (qty * price * dis) / 100;
        tr.find('.amount').val(amt);
        total();
    });
});

function total() {
    var t = 0;
    $('.amount').each(function(i, e) {
        var amt = $(this).val() - 0;
        t += amt;
    });
    $('.total').html(t);
}

function addnewrow() {


    var n = ($('.detail tr').length - 0) + 1;  
    var tr = '<tr>' +
        '<td class="no">' + n + '</td>' +
        '<td><input type="text" class="form-control productname" name="productname[]"></td>' +
        '<td><input type="text" class="form-control quantity" name="quantity[]"></td>' +
        '<td><input type="text" class="form-control price" name="price[]"></td>' +
        '<td><input type="text" class="form-control discount" name="discount[]"></td>' +
        '<td><input type="text" class="form-control amount" name="amount[]"></td>' +
        '<td><a href="#" class="remove">Delete</td>' +
        '</tr>';
    $('.detail').append(tr);
}


function update_tbl(){

var n = ($('.detail tr').length - 0) + 1;

var tr = $(this).parent().parent();

        var qty = tr.find('.quantity').val();
        var price = tr.find('.price').val();

        var dis = tr.find('.discount').val();
        var amt = (qty * price) - (qty * price * dis) / 100;
        tr.find('.amount').val(amt);
        total();  

}

/*var b = jQuery("#inventory_form").validate({
      ignore: [],
      rules: {
        'productname[]': {
          required: true,
          minlength: 2,
          maxlength: 100,
          lettersonly: true
        },
        cphone: {
          required: true,
          minlength: 2,
          maxlength: 16,
          number:true,
        },


      },
      errorElement: "span",
      errorClass: "help-inline-error",
    }); */


// Code to capture the user action of CTRL+S pressed
document.addEventListener("keydown", function(e) {
      if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey))      {
        e.preventDefault();
        //your implementation or function calls
         $('#save_btn').click();
      }   
    }, false);


// jquery validation rules for inventory table

var count = $('#productname').length;
console.log(count);
$(document).ready(function(){

$('#inventory_form').validate({

  rules:{
       'productname[]':{
          required: true,          
       },
       'quantity[]':{
           required: true,
           number:true
       },
       'price[]':{
           required: true,
           number:true
       },
       'discount[]':{
           required: true,
           number:true
       },
       'amount[]':{
         required:true,
         number:true
       }

   },
   messages:{
        'productname[]':{
          required: 'Please enter product name'
        },
        'quantity[]':{
          required: 'Please enter product quantity',
          number:'quantity must be in numbers'
        },
        'price[]':{
          required: 'Please enter product price',
          number:'price must be in numbers'
        },
        'discount[]':{
          required: 'Please enter product discount',
          number:'discount must be in numbers'         

        },
        'amount[]':{
          required: 'Please enter product amount',
          number:'discount must be in numbers'
        }

   },   
   errorClass: "text text-danger"



});






});
4
  • Use the .rules() method to add rules dynamically. Also use the search feature of SO to see examples. Commented May 20, 2017 at 14:49
  • Hi Sparky i followed all the steps according to the answer you suggested me but it is still not working for me i used .rules method but still it is not working according to my expectation..!!! And the console is showing the error in the jquery.min.js file. Commented May 22, 2017 at 8:54
  • "not working according to expectations" and "console is showing the error" simply mean you made some mistakes, and I cannot possibly know what you did wrong. Please edit your question with an amendment showing exactly what you've tried. Otherwise, if it's too much or too confusing, then start a whole new question. In either case, take enough time to create a CONCISE, yet complete, demonstration of the problem. See: stackoverflow.com/help/mcve Commented May 22, 2017 at 15:26
  • Thanks sparky !! yes i did what you said and i rewrite the code in all different way and it works for me..!! Commented May 23, 2017 at 5:33

1 Answer 1

-1

Use "on" function instead "delegate":

(function() {
$('#add').click(function() {
    addnewrow();
});
$('body').on( 'click','.remove', function(event) {
    $(this).parent().parent().remove();
    update_tbl();
    event.preventDefault();

});
$('body').on('keyup','.quantity,.price,.discount',  function() {
    var tr = $(this).parent().parent();

    var qty = tr.find('.quantity').val();
    var price = tr.find('.price').val();

    var dis = tr.find('.discount').val();
    var amt = (qty * price) - (qty * price * dis) / 100;
    tr.find('.amount').val(amt);
    total();
});

});

Sign up to request clarification or add additional context in comments.

6 Comments

you can view the code here jsfiddle.net/harihp/8703fjga
No it is not working ..!! not even creating a dynamic row..!!
did you look into the above fiddle ? . do you have any console errors ?
yes i checked it manually now the validation is not working properly..!!!
still the validation works only on first row not on the others that is generated dynamically when i click on the add new row button..!!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.