Home > Back-end >  MVC 5 Option Empty Line With JavaScript
MVC 5 Option Empty Line With JavaScript

Time:03-12

$('#DepartmentCode').change(function () {
    var empName = $('#Employee_No');
    var department = $('#DepartmentCode').val();
    empName.empty();

    $.ajax({
        url: "/LeaveRequestEntry/GetEmployeesByDept",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify({ ClassCode: department }),
        success: function (data) {
            $.each(data, function (index, option) {
                empName.append('<option value='   option.Value   '>'   option.Text   '</option>');
            });
        }
    });
});

This is my JavaScript code.

   ViewBag.Employee = employeeRepository.GetAllByDepartment(ClassCode).Select(e => new SelectListItem { Text = e.Full_Name   "_"   e.No, Value = e.No });
    return Json(new SelectList(ViewBag.Employee, "Value", "Text"));

This is my controller part.

    <div >
        @Html.DropDownList("Department", new SelectList(ViewBag.DepartmentList, "Value", "Text"), LeaveRequestEntryRes.SelectableMessage, new { @class = "ui fluid dropdown", @id = "DepartmentCode" })
    </div>
    <div >
        @Html.DropDownList("Employee_No", new SelectList(ViewBag.EmployeeList, "Value", "Text"), LeaveRequestEntryRes.SelectableMessage, new { @class = "ui fluid dropdown" })
    </div>

There are 2 options in the html part. When I select a department, the employees of that department come. My problem is that one of them is always selected. I want to click and select. how do i fix it so that if i click it ?? Sorry for my English. :)

CodePudding user response:

Could you not just set a placeholder option above the loop in the success?

for example:

empName.append('<option value="" selected>Select an option</option>');

// The loop to populate
  • Related