How to pass the uuid value to all the input fields of a form that are added dynamically using JavaScript?

Viewed 128

My form has a uuid text field. The uuid is auto-generated. I want to pass this uuid to all the dynamically added fields. Form below has two fields one is for the uuid and the other one is for the SKU number. Please kindly guide me.

<html>
<body>
         <form>
        <table id="dynamic_field">
             <td>
              <div>
               <input type="hidden" class="form-control"  name="uuid[]"/>
              </div>
             </td>
             
             <td>&nbsp;</td>
            
             <td>
              <div>
               <label>Enter SKU</label>
                <input type="text" class="form-control"  name="SKU[]" />
              </div>
             </td>
    <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td> 
            <input type="submit" name="submit" id="submit" value="Submit">
        </table>
            </form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
        
            <script type="text/javascript">
              $(document).ready(function(){
                var max_input = 7;
                var i = 1;
            
              $("#add").click(function(){if (i < max_input) {
                  i++;
                  $('#dynamic_field').append('<tr id="row'+i+'"><td><div><input type="hidden" class="form-control"  name="uuid[]"/></div></td><td>&nbsp;</td><td><div><label>Enter SKU</label><input type="text" class="form-control"  name="SKU[]" /></div></td><td>&nbsp;</td><td valign="bottom"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>');  
                }});
            
                $(document).on('click', '.btn_remove', function(){  
                  var button_id = $(this).attr("id");   
                  $('#row'+button_id+'').remove();  
                });
            
                $("#submit").on('click',function(){
                  var formdata = $("#main-form").serialize();
                  $.ajax({
                    url   :"action.php",
                    type  :"POST",
                    data  :formdata,
                    cache :false,
                    success:function(result){
                      alert(result);
                      $("#main-form")[0].reset();
                    }
                  });
                });
              });
            </script>
0 Answers
Related