skip to Main Content

there is a part of my form in which a user can enter the building and room and click the add button if they want to enter another building and room. I am using AJAX to populate the rooms based on the building selection. It works for the first set but once I click add and the page reloads it resubmits the Ajax call therefore deleting the option the user selected.

Once I click add and there are two dropdowns for building and two for rooms, regardless of which building dropdown I click, it only affects the second room dropdown.

Any guidance would be appreciated.

            for (var a = 0; a < @Model.OnCampusSchedules.Count; a++) {
                var buildingSelectId = '#BuildingSelect_' + a;
                var roomSelectId = '#RoomSelect_' + a;

                var selectedBuildingValue = $(buildingSelectId).val();
                var selectedRoomValue = $(roomSelectId).val();

                $(buildingSelectId).change(function () {
                    var selectedBuilding = $(this).val();
                    var roomSelect = $(roomSelectId);

                    $(roomSelect).empty();

                    roomSelect.addClass('spinner').prop('disabled', true);


                    $.ajax({
                        url: '@Url.Action("GetRoomNumbers", "External")',
                        type: 'GET',
                        data: {
                            building: selectedBuilding,
                        },
                        success: function (data) {
                            if (data.length > 0){
                                $(data).each(function (index, item) {
                                    roomSelect.append('<option value="' + item + '">' + item + '</option>');
                                });
                                roomSelect.val(selectedRoomValue);
                                roomSelect.prop('disabled', false);
                            }
                        },
                        error: function () {
                            console.error("Failed to get rooms");
                        },
                        complete: function () {
                            roomSelect.removeClass('spinner');
                        }
                    });
                }).change();

                $(roomSelectId).val(selectedRoomValue);
            }
        });
            <div class="tab-content" id="schedule">
                <h2 class="h3">Schedule</h2>
                @for(a = 0; a < Model.OnCampusSchedules.Count; a++)
                {
                    @if (Model.OnCampusSchedules[a].IsDeleted)
                    {
                        <input type="hidden" asp-for="OnCampusSchedules[a].IsDeleted" value="true" />
                    }
                    else
                    {
                            <div class="col">
                                <div class="form-group">
                                    <span asp-validation-for="OnCampusSchedules[a].StartTime"></span>
                                    <label asp-for="OnCampusSchedules[a].StartTime" class="font-weight-bold">Start Time: <span class="required" aria-hidden="true">*</span></label>
                                    <input asp-for="OnCampusSchedules[a].StartTime" type="time" aria-required="true" class="form-control" required />
                                </div>
                            </div>

                            <div class="col">
                                <div class="form-group">
                                    <span asp-validation-for="OnCampusSchedules[a].EndTime"></span>
                                    <label asp-for="OnCampusSchedules[a].EndTime" class="font-weight-bold">End Time: <span class="required" aria-hidden="true">*</span></label>
                                    <input asp-for="OnCampusSchedules[a].EndTime" type="time" aria-required="true" class="form-control" required />
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col">
                                <div class="form-group">
                                    <span asp-validation-for="OnCampusSchedules[a].Building"></span>
                                    <label asp-for="OnCampusSchedules[a].Building" class="font-weight-bold">Building: <span class="required" aria-hidden="true">*</span></label>
                                    <select asp-for="OnCampusSchedules[a].Building" asp-items="Model.Buildings" id="BuildingSelect_@a" aria-required="true" class="form-control" required></select>
                                </div>
                            </div>
                            <div class="col">
                                <div class="form-group">
                                    <span asp-validation-for="OnCampusSchedules[a].Room"></span>
                                    <label asp-for="OnCampusSchedules[a].Room" class="font-weight-bold">Room: <span class="required" aria-hidden="true">*</span></label>
                                    <select asp-for="OnCampusSchedules[a].Room" asp-items="Model.Rooms" id="RoomSelect_@a" aria-required="true" class="form-control"></select>
                                </div>
                            </div>
                        </div>
                        <div class="text-right">
                            <button class="btn btn-danger @(Model.OnCampusSchedules.Where(a => !a.IsDeleted).Count() == 1 ? "d-none" : "")"
                                    formnovalidate type="submit" id="delbutton[@a]"
                                    asp-action="Delete" asp-controller="External" asp-all-route-data="@(new Dictionary<string, string> { { "Id", a.ToString() } })">
                                Delete Schedule
                            </button>
                        </div>

                        <hr />
                    }
                }


            <div class="text-right">
                <button class="btn btn-success" formnovalidate type="submit" id="addbutton" asp-action="Add" asp-controller="External">
                    Add Schedule 
                </button>
            </div>

            <div class="form-row">
                <div class="col-sm-6 offset-sm-3 col-md-4 offset-md-4">
                    <div class="form-group mt-3">
                        <button id="Submit" type="submit" class="btn btn-sm btn-block btn-secondary">Submit</button>
                    </div>
                </div>
            </div>
            </div>
        </form>
    </div> 
</div>
        public IActionResult Add(ExternalForm externalForm)
        {
            externalForm.OnCampusSchedules.Add(new OnCampusSchedule(_processUser));

            return View("Index", externalForm);
        }

2

Answers


  1. When you have a button inside a form, when you click you will submit the form. You need to prevent that. Inside the the button event handler add this: e.preventDefault();

    Login or Signup to reply.
  2. Just modify your js code like below:

    <script>
            $(document).ready(function () {
                $('#schedule').on('change', '[id^="BuildingSelect_"]', function () {
                    var index = $(this).attr('id').split('_')[1];
                    var buildingSelectId = '#BuildingSelect_' + index;
                    var roomSelectId = '#RoomSelect_' + index;
    
                    var selectedBuilding = $(buildingSelectId).val();
                    var roomSelect = $(roomSelectId);
    
                    roomSelect.empty();
                    roomSelect.addClass('spinner').prop('disabled', true);
    
                    $.ajax({
                        url: '@Url.Action("GetRoomNumbers", "External")',
                        type: 'GET',
                        data: {
                            building: selectedBuilding,
                        },
                        success: function (data) {
                            if (data.length > 0) {
                                $(data).each(function (index, item) {
                                    roomSelect.append('<option value="' + item + '">' + item + '</option>');
                                });
                                roomSelect.prop('disabled', false);
                            }
                        },
                        error: function () {
                            console.error("Failed to get rooms");
                        },
                        complete: function () {
                            roomSelect.removeClass('spinner');
                        }
                    });
                });
            });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search