0

I want to append table row with dynamic drop down list but get error declaration or syntax error in jquery code. how to fix it?

$(".addtable").click(function () {
    debugger;
     $("#fields tbody").append("<tr><td>@Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" })</td><td><input type="number" class="form-control" name=" Quantity" required></td><td><button type="button" class="btn btn-primary addtable">Add More</button><a href="javascript:void(0);" class="btn btn-primary remCF">Remove</a></td></tr>");

});

1 Answers1

0

After testing this approach in a dummy project, I've discovered two issues:

  1. You need to wrap your string with single-quotes instead of double-quotes, ie, change .append("...") to .append('...') .
  2. Html.DropDownListFor() produces a string that has a newline character, which causes a line break in the javascript string, which throws a syntax error. So you need to do something like: .append('@(Html.Raw(Html.DropDownListFor(...).ToString().Replace(System.Environment.NewLine, "")))') , which looks really ugly, but it works in my dummy project.`

So try:

$(".addtable").click(function () {
debugger;
 $("#fields tbody").append('<tr><td>@(Html.Raw(Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" }).ToString().Replace(System.Environment.NewLine, "")))</td><td><input type="number" class="form-control" name=" Quantity" required></td><td><button type="button" class="btn btn-primary addtable">Add More</button><a href="javascript:void(0);" class="btn btn-primary remCF">Remove</a></td></tr>');
});
reasonet
  • 145
  • 12