1

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"));
    }
2
  • did you check your html generated ? check your browsers elements tab . Also , do console.log(data) inside your success function see what its giving . Commented Jan 7, 2021 at 13:28
  • @Swati <option value='3'>Test</option><option value='4'>Test 2</option> that is log of option created Commented Jan 7, 2021 at 13:57

1 Answer 1

1

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>

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

1 Comment

Thank you so much. That resolve my issue.

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.