0

I'm currently working on some forms for a CRUD. In one of my forms, I have to be able to add components dynamically, so I created an "add more" button, which generates 2 fields extra, one where a dropdown menu should appear with all the items from my DB, and another with an input field.

Form

The input field ("Amount") is working fine, but I couldn't manage to integrate the data from the DB into the Jquery script to generate the extra fields when I add the values from the DB, then the "Add more" button doesn't work. The value of the second dropdown ("Tube") was hardcoded just to test the layout. Any idea of how can solve this?

<div class="table-responsive">
  <table class="table table-bordered" id="dynamic_field">
    <tr>
      <td>
        <select class="form-control" name="ProductGroup" id='Product__field'>
          <?php
              $sql = DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get();
              foreach ($sql as $row) {
                echo "<option value='".$row->id."'>" . $row->Product_Name. "</option>";
              }
              ?>
        </select>
      </td>
    </tr>
    <tr>
      <td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td>
      <td><button type="button" name="add" id="add" class="btn btn-success btn_add">Add More</button></td>
    </tr>

and this is my jquery code so that each time I press Add more a new Dropdown Menu and an input field are generated

<script type="text/javascript">
  $(document).ready(function() {
    var postURL = "<?php echo url('addmore'); ?>";
    var i = 1;

    var array = {{ json_encode(DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get()) }};
    $('#add').on('click', '.btn_add', function() {
         i++;
         $('#dynamic_field').append('<tr id="row' + i + '" class="dynamic-added"><td><select id="select_'+i+'"class="form-control" name="Item[]"></select><tr id="row' + i +
           '" class="dynamic-added"></td><td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
       });
    array.forEach(function(row){
        $('#select_'+i).append('<option value="'+row["id"]+'" >'+row["Product_Name"]+'</option>');
    });
          $(document).on('click', '.btn_remove', function() {
          var button_id = $(this).attr("id");
          $('#row' + button_id + '').remove();
        });
</script>

I get the Error: "Uncaught SyntaxError: Unexpected token &" on the line "var array = [{"id":24,"Product_Name":"B2C Kit"},{"id":25,"Product_Name":"B2B "},{"id":26,"Product_Name":"B2B Kit "},{"id":27,"Product_Name":"Swab"},{"id":28,"Product_Name":"Tube"}];"

Last Tried code:

            <div class="table-responsive">
              <table class="table table-bordered" id="dynamic_field">
                <tr>
                  <td>
                    <select class="form-control" name="ProductGroup" id='Product__field'>
                      <?php
                          $sql = DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get();
                          foreach ($sql as $row) {
                            echo "<option value='".$row->id."'>" . $row->Product_Name. "</option>";
                          }
                          ?>
                    </select>
                  </td>
                </tr>
                <tr>
                  <td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td>
                  <td><button type="button" name="add" id="add" class="btn btn-success btn_add">Add More</button></td>
                </tr>
              </table>
              <div class="row">
                <div class="col-md-12"></div>
                <div class="form-group col-md-12">
                  <button type="submit" class="btn btn-success" style="margin-left:38px">Add Kit type</button>
                </div>
              </div>
            </div>


    <script type="text/javascript">
  $(document).ready(function() {
    var postURL = "<?php echo url('addmore'); ?>";
    var i = 1;

    var array = [<?php DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get() ?>];
    array.forEach(function(row){
      $('#select_'+i).append('<option value="'+row["id"]+'" >'+row["Product_Name"]+'</option>');
    });
    $('#add').on('click', function() {
    i++;
    $('#dynamic_field').append('<tr id="row' + i + '" class="dynamic-added"><td><select id="select_' + i + '"class="form-control" name="Item[]"></select><tr id="row' + i +
      '" class="dynamic-added"></td><td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
  });
});

    $(document).on('click', '.btn_remove', function() {
      var button_id = $(this).attr("id");
      $('#row' + button_id + '').remove();
    });
    </script>
2
  • 1
    so you want to add same div/data when user click on add button. Am i right? Commented Apr 17, 2019 at 7:30
  • @MaulikShah Yes, I want all the dropdowns that are generated with the same data as the first one Commented Apr 17, 2019 at 7:32

3 Answers 3

1

Try with this,

<td><button type="button" name="add" id="add" class="btn btn-success btn_add">Add More</button></td>
<div class="field_wrapper">
     {{-- Extra fields when User click on add --}}
</div>

You have to call script when user click on that particular button like this,

$(document).ready(function () {
            var maxField = 10; //Input fields increment limitation
            var addButton = $('.btn_add'); //Add button selector
            var wrapper = $('.field_wrapper'); //Input field wrapper
            var fieldHTML = '<div class="form-group">' +
                '<a href="javascript:void(0);" class="remove_button float-right">&nbsp;<i class="fa fa-minus"></i></a>' +
                '<label for="field-1" class="control-label">Extra Ingredients</label><br>' +
                // Here put your logic for dropdown and other field
                '</div>'; //New input field html
            var x = 1; //Initial field counter is 1

            //Once add button is clicked
            $(addButton).click(function () {
                //Check maximum number of input fields
                if (x < maxField) {
                    x++; //Increment field counter
                    $(wrapper).append(fieldHTML); //Add field html
                }
            });

            //Once remove button is clicked
            $(wrapper).on('click', '.remove_button', function (e) {
                e.preventDefault();
                $(this).parent('div').remove(); //Remove field html
                x--; //Decrement field counter
            });
        });

Hope this helps :)

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

8 Comments

Thanks for the quick answer!, I tried it but when I click the button still nothing happens :S
check console and see any error are throwing are not.
Error "Uncaught SyntaxError: Unexpected token &" and it shows this when I click on it "var array = [{&quot;id&quot;:24,&quot;Product_Name&quot;:&quot;B2C Kit&quot;},{&quot;id&quot;:25,&quot;Product_Name&quot;:&quot;B2B Kit myfairtrade&quot;},{&quot;id&quot;:26,&quot;Product_Name&quot;:&quot;B2B Kit &quot;},{&quot;id&quot;:27,&quot;Product_Name&quot;:&quot;Swab&quot;},{&quot;id&quot;:28,&quot;Product_Name&quot;:&quot;Tube&quot;}];"
could you please upload your last tried code and error of that code.
the problem here was that there was a class added to the listener.
|
1

Remove the extra class from your onclick listener $('#add').on('click', '.btn_add', function() { to $('#add').on('click', function() {

you can also use $(document).on('click', '#add, .btn_add', function() { for multiple selectors.

    $(document).ready(function() {
      var postURL = "<?php echo url('addmore'); ?>";
      var i = 1;

      var array = [{
        "id": 24,
        "Product_Name": "B2C Kit"
      }, {
        "id": 25,
        "Product_Name": "B2B "
      }, {
        "id": 26,
        "Product_Name": "B2B Kit "
      }, {
        "id": 27,
        "Product_Name": "Swab"
      }, {
        "id": 28,
        "Product_Name": "Tube"
      }]

      $('#add').on('click', function() {
        i++;
        $('#dynamic_field').append('<tr id="row' + i + '" class="dynamic-added"><td><select id="select_' + i + '"class="form-control" name="Item[]"></select><tr id="row' + i +
          '" class="dynamic-added"></td><td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');

        array.forEach(function(row) {
          $('#select_' + i).append('<option value="' + row["id"] + '" >' + row["Product_Name"] + '</option>');
        });
      });
      $(document).on('click', '.btn_remove', function() {
        var button_id = $(this).attr("id");
        $('#row' + button_id + '').remove();
      });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="table-responsive">
  <table class="table table-bordered" id="dynamic_field">
    <tr>
      <td>
        <select class="form-control" name="ProductGroup" id='Product__field'>
          <?php
              $sql = DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get();
              foreach ($sql as $row) {
                echo "<option value='".$row->id."'>" . $row->Product_Name. "</option>";
              }
              ?>
        </select>
      </td>
    </tr>
    <tr>
      <td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td>
      <td><button type="button" name="add" id="add" class="btn btn-success btn_add">Add More</button></td>
    </tr>
    </table>
    </div>

9 Comments

Thanks, this works without my data, once I add my var array with the data from the DB the button doesn't work anymore
@matilarab that'll depend on how you get the data from db, and please change var array = {} to var array = [php code herer]
Did that, but still have the same issue, the Data si not showing
Yes, I will have to change some things because now each time I click, new fields generate. but my main concern is that the data is still not showing on the dropdown
I can see them now. Is there not any way that I can do it with my database?
|
0

I found a solution for my problem, thaknks for the help!

        <div class="table-responsive">
          <table class="table table-bordered" id="dynamic_field">
            <tr>
              <td>
                <select class="form-control" name="ProductGroup" id='Product__field'>
                  <?php
                      $sql = DB::connection('log_inv')->table('logisticsinv')->select('id', 'Product_Name')->get();
                      foreach ($sql as $row) {
                        echo "<option value='".$row->id."'>" . $row->Product_Name. "</option>";
                      }
                      ?>
                </select>
              </td>
            </tr>
            <tr>
              <td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td>
              <td><button type="button" name="add" id="add" class="btn btn-success btn_add">Add More</button></td>
            </tr>
          </table>
          <div class="row">
            <div class="col-md-12"></div>
            <div class="form-group col-md-12">
              <button type="submit" class="btn btn-success" style="margin-left:38px">Add Kit type</button>
            </div>
          </div>
        </div>
</center>

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

<script type="text/javascript">
var array = {!!json_encode($sql)!!};
$(document).ready(function() {
  var postURL = "<?php echo url('addmore'); ?>";
  var i = 1;

  $('#add').on('click', '.btn_add', function() {
    i++;
    $('#dynamic_field').append('<tr id="row' + i + '" class="dynamic-added"><td><select id="select_' + i + '"class="form-control" name="Item[]"></select><tr id="row' + i +
      '" class="dynamic-added"></td><td><input type="text" name="Amount[]" placeholder="Amount" class="form-control" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');

    array.forEach(function(row) {
      $('#select_' + i).append('<option value="' + row["id"] + '" >' + row["Product_Name"] + '</option>');
    });
  });
  $(document).on('click', '.btn_remove', function() {
    var button_id = $(this).attr("id");
    $('#row' + button_id + '').remove();
  });
});
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.