Fahad Ejaz Butt
Fahad Ejaz Butt

Reputation: 113

Create select dynamically and add select options from database using jQuery in asp.net core

I am trying to create select dynamically using jQuery. I am able to create the select with the desired naming. But when I am trying to add options, which I am fetching from the database using ajax call. Options are not showing up.

My view is below.

 <div class="form-group row" id="data-url-ingredient" data-request-url="@Url.Action("GetIngredientList", "Products")">
  <input name="index" id="index" type="hidden" value="0" />
   <div class="col-md-10">
     <table class="table table-borderless tblIngredient">
        <thead>
            <tr>
                <th>Ingredient</th>
                <th>Quantity</th>
                <th><button type='button' class='btn btn-air-info btn-sm add-row' style='border-radius:30px'>MORE</button></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

And below is my jquery code.

$(document).ready(function () {
$('.add-row').on('click', function () {
    var t = $('.tblIngredient');
    var index = $('#index').val();
    var link = $('#data-url-ingredient').data('request-url');
    var drop = "<select class='form-control txtingredient' name='ProductIngredentList['" + $("#index").val().trim() + "'].Id'></select>"
    t.append('<tr> <td>' +
        drop +
        "</td>" +
        "<td><input type='text' class='form-control txtquantity' name='ProductIngredentList['" + $("#index").val().trim() + "'].Quantity' /></td>'" +
        "<td><button type='button' class='btn btn-air-warning btn-sm' style = 'border-radius : 30px''>DELETE</button></td></tr>");
    $.ajax({
        type: "POST",
        url: '/Admin/Products/GetIngredientList',
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (data) {
            var items = "<option selected disabled>Select ingredient</option>";;
            $.each(data, function (i, ingredient) {
                items += "<option value='" + ingredient.value + "'>" + ingredient.text + "</option>";
            });
            $(drop).append(items);
        }
    });
    index = parseInt(index) + 1;
    $('#index').val(index);
    reindex();
});
function reindex() {
    $('.tblIngredient').each(function (index1, index2) {
        index1 = 0;
        index2 = 0;

        $(this).find(".txtingredient").each(function () {
            var prefixName = "ProductIngredentList[" + index1 + "].Id";
            this.name = this.name.replace(/ProductIngredentList\[\d+\].Id/, prefixName);
            index1++;
        });
        $(this).find(".txtquantity").each(function () {
            var prefixQuantity = "ProductIngredentList[" + index2 + "].Quantity";
            this.name = this.name.replace(/ProductIngredentList\[\d+\].Quantity/, prefixQuantity);
            index2++;
        });
    });
}
$(document).on('click', 'button.btn-air-warning', function () {
    $(this).closest('tr').remove();
    reindex();
    return false;
});

Here is the output I am getting select is created, but there is no option:

enter image description here

Below is the controller action for options values.

public async Task<IActionResult> GetIngredientList()
    {
        var ingredentList = await _context.TblIngredient.Where(s => s.Status == true).ToListAsync();
        return Json(new SelectList(ingredentList, "Id", "Name"));
    }

Upvotes: 1

Views: 1593

Answers (1)

Swati
Swati

Reputation: 28522

Before ajax call you are already appending your select-box to your tblIngredient so that's why $(drop).append(items); is not working . Instead you can use $(".tblIngredient tr:last").find('.txtingredient').html(items) this will find tr which is last(added now) in that select-box and using .html() append your options.

Demo Code :

$('.add-row').on('click', function() {
  var t = $('.tblIngredient');
  var drop = "<select class='form-control txtingredient' name='ProductIngredentList[1].Id'></select>"
  t.append('<tr> <td>' +
    drop +
    "</td>" +
    "<td><input type='text' class='form-control txtquantity' name='ProductIngredentList[1].Quantity' /></td>'" +
    "<td><button type='button' class='btn btn-air-warning btn-sm' style = 'border-radius : 30px''>DELETE</button></td></tr>");
  /* $.ajax({
       type: "POST",
       url: '/Admin/Products/GetIngredientList',
       contentType: 'application/json; charset=utf-8',
       dataType: "json",
       success: function (data) {
          ;;
           $.each(data, function (i, ingredient) {*/
  var items = "<option selected disabled>Select ingredient</option>"
  items += "<option value='ddd'>dddsd</option>";
  /*});*/
  //use this
  $(".tblIngredient tr:last").find('.txtingredient').html(items)

  /*}
    });*/
  //some other codes..
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class='tblIngredient'>
</table>

<button class="add-row">Add row </button>

Upvotes: 1

Related Questions