Search code examples
c#htmlrazorasp.net-core-2.0

ASP.NET Core 2.0 set focus on a input element


I have an older ASP.NET Core MVC razor partial form with 2 input fields, I am trying to set the focus on the first input field on the form load, and when the user changes the value I want to then change the focus to the second input box. This is my first project working with ASP.NET Core 2.0 razor pages.

The issue is when I try to use HTML, Java, or razor code to set the focus, it does not work. I am hoping someone can see where I am going wrong. Thank you in advance.

Update Full script

<script>
  
    $(document).ready(function () {

        $('#ordersrefresh').on("click", function (e) {
            window.location.reload(true);
        });

        $('#orderstart').on("click", function (e) {
            $('#orderstartpick').empty();
            $('#orderstartdrop').empty();
            $('#orderstartpriority').empty();
           
            //$('#orderstartmodal').modal({ backdrop: 'static', keyboard: false, show: true });

            $.getJSON("/orders/orderlist/picks", function (picks) {
                picks.forEach(function (item) {
                    $('#orderstartpick').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/drops", function (drops) {
                drops.forEach(function (item) {
                    $('#orderstartdrop').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/priorities", function (priorities) {
                priorities.forEach(function (item) {
                    $('#orderstartpriority').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            // shows the partial form
            $.getJSON("/orders/orderlist/conn", function (conn) {
                if (conn == "true") {
                    $('#orderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
                     $('#orderstartmodal').on('shown.bs.model',function () {
                        $('#orderstartpick').focus();
                    })
                }
                else {
                    $('#noorderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
                  
                }
            });

            // Set focus on the drop input after the pick input has changed - Working
            $('#orderstartpick').change(function () {
                $('#orderstartdrop').focus();
            });
        });

        


        $('#ordermodif').on("click", function (e) {
            $('#ordermodifid').empty();
            $('#ordermodifpick').empty();
            $('#ordermodifdrop').empty();
            $('#ordermodifpriority').empty();

            //$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });

            $.getJSON("/orders/orderlist/picks", function (picks) {
                picks.forEach(function (item) {
                    $('#ordermodifpick').append('<option value="' + item + '">' + item + '</option>');
                });
            });

           ("/orders/orderlist/drops", function (drops) {
                drops.forEach(function (item) {
                    $('#ordermodifdrop').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/priorities", function (priorities) {
                priorities.forEach(function (item) {
                    $('#ordermodifpriority').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/ids", function (ids) {
                var idscount = 0;
                ids.forEach(function (item) {
                    $('#ordermodifid').append('<option value="' + item + '">' + item + '</option>');
                    ++idscount;
                });

                if (idscount > 0) {
                    $('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                }
                else {
                    $('#noordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                }
            });
        });

        $('#ordermodifmodal').on("shown.bs.modal", function (e) {
            var ordermodifid = $('#orderidmodifcurrent').val();
            $.getJSON("/orders/orderlist/order", { orderid: ordermodifid }, function (order) {
                $('#ordermodifmodal #ordermodifpick').val(order.pick.name);
                $('#ordermodifmodal #ordermodifdrop').val(order.drop.name);
                $('#ordermodifmodal #ordermodifpriority').val(order.priority);
            });
        });

        $('#ordermodifmodal #ordermodifid').change(function (e) {
            var ordermodifid = $(this).find("option:selected").val();
            $.getJSON("/orders/orderlist/order", { orderid: ordermodifid }, function (order) {
                $('#ordermodifmodal #ordermodifpick').val(order.pick.name);
                $('#ordermodifmodal #ordermodifdrop').val(order.drop.name);
                $('#ordermodifmodal #ordermodifpriority').val(order.priority);
            });
        });

        function DeleteRenderer(data, type, row) {
            var StatusColumn = row.status;

            if (StatusColumn.includes("Cancelling") || (StatusColumn.includes("Canceled"))) {
                return "<button class='btn btn-outline-info' disable>Delete</button>";
            }
            else {
                return "<button class='btn btn-outline-danger'd>Delete</button>";
            }
        }

        function CancelRenderer(data, type, row) {
            var StatusColumn = row.status;

            if (StatusColumn.includes("Assigned") || (StatusColumn.includes("Pending"))) {
                return "<button class='btn btn-outline-warning'>Cancel</button>";
            }
            else {
                return "<button class='btn btn-outline-info' disabled>Cancel</button>";
            }
        }

        function ModifyRenderer(data, type, row) {
            var StatusColumn = row.state;

            if (StatusColumn.includes("Assigned") || (StatusColumn.includes("Pending"))) {
                return "<button class='btn btn-outline-info'>Modify</button>";
            }
            else {
                return "<button class='btn btn-outline-info' disabled>Modify</button>";
            }
        }

        function DateRenderer(data) {
            return moment(data).format('DD/MM/YYYY HH:mm:ss');
        }

        var table = $('#orders').DataTable({
            "processing": false, // for show progress bar
            "serverSide": false, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "lengthMenu": [[20, 50, -1], [20, 50, "All"]],
            "pagingType": "simple",
            "ajax": {
                "url": "/Orders/OrderList/data", // for client side /LoadDataAll
                "type": "GET",                   // for client side "GET"
                "datatype": "json"
            },
            "select": 'single',
            "columns": [
                { "data": "created", "render": DateRenderer, "autoWidth": true },
                { "data": "wmsid", "name": "WMSID", "autoWidth": true },
                { "data": "index", "name": "OrderID", "autoWidth": true },
                { "data": "pick.name", "name": "Pick", "autoWidth": true },
                { "data": "drop.name", "name": "Drop", "autoWidth": true },
                { "data": "sequence", "name": "Sequence", "autoWidth": true },
                { "data": "status", "name": "Status", "autoWidth": true },
                { "data": "priority", "name": "Priority", "autoWidth": true },
                { "data": "null", "render": ModifyRenderer, "orderable": false },
                //{ "data": "null", "render": CancelRenderer, "orderable": false },
                //{ "data": "null", "render": DeleteRenderer, "orderable": false },
            ]
        });

        $('#orders tbody').on('click', 'button', function () {
            var data = table.row($(this).parents('tr')).data();
            var buttontext = $(this).text();

            var token = $("[name=__RequestVerificationToken]").val();
            $('input[name="orderidcurrenthidden"]').val(data.wmsid);

            var ordertext = data.wmsid;

            if (buttontext.toUpperCase() == 'MODIFY') {
                $('#ordermodifpick').empty();
                $('#ordermodifdrop').empty();
                $('#ordermodifpriority').empty();

                $('#orderidmodifcurrent').val($('input[name="orderidcurrenthidden"]').val());

                //$('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                $.ajaxSetup({ async: false });

                $.getJSON("/orders/orderlist/picks", function (picks) {
                    picks.forEach(function (item) {
                        $('#ordermodifpick').append('<option value="' + item + '">' + item + '</option>');
                    });
                });

                $.getJSON("/orders/orderlist/drops", function (drops) {
                    drops.forEach(function (item) {
                        $('#ordermodifdrop').append('<option value="' + item + '">' + item + '</option>');
                    });
                });

                $.getJSON("/orders/orderlist/priorities", function (priorities) {
                    priorities.forEach(function (item) {
                        $('#ordermodifpriority').append('<option value="' + item + '">' + item + '</option>');
                    });
                });

                //$.getJSON("/orders/orderlist/ids", function (ids) {
                //    var idscount = 0;
                //    ids.forEach(function (item) {
                //        $('#ordermodifid').append('<option value="' + item + '">' + item + '</option>');
                //        ++idscount;
                //    }
                //});

                $.getJSON("/orders/orderlist/conn", function (conn) {
                    if (($('#ordermodifpick option').length > 0) &&
                        ($('#ordermodifdrop option').length > 0) &&
                        ($('#ordermodifpriority option').length > 0) &&
                        (conn == "true")) {
                        $('#ordermodifmodal .modal-title').text('MODIFY ORDER: ' + ordertext);
                        $('#ordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                    else {
                        $('#noordermodifmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                });

                $.ajaxSetup({ async: true });
            }
            else if (buttontext.toUpperCase() == 'CANCEL') {
                $.post('/orders/orderlist?handler=ordercancel', {
                    orderid: data.wmsid,
                    __RequestVerificationToken: token,
                }, function (strResult) {
                    if (strResult == "true") {
                        $('#ordercancelmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                    else {
                        $('#noordercancelmodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                });
            }
            else if (buttontext.toUpperCase() == 'DELETE') {
                $.post('/orders/orderlist?handler=orderdelete', {
                    orderid: data.wmsid,
                    __RequestVerificationToken: token,
                }, function (strResult) {
                    if (strResult == "true") {
                        $('#orderdeletemodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                    else {
                        $('#noorderdeletemodal').modal({ backdrop: 'static', keyboard: false, show: true });
                    }
                });
            }
        });

        setInterval(function () {
            table.ajax.reload(null, false); // user paging is not reset on reload
        }, 5000);

        $(window).on('resize', function () {
            $('#orders').attr("style", "");
            table.columns.adjust();
        });

        $("input[id$='orderstartpick']").focus();

      
    });

</script>

script

$('#orderstart').on("click", function (e) {
            $('#orderstartpick').empty();
            $('#orderstartdrop').empty();
            $('#orderstartpriority').empty();
           
            //$('#orderstartmodal').modal({ backdrop: 'static', keyboard: false, show: true });

            $.getJSON("/orders/orderlist/picks", function (picks) {
                picks.forEach(function (item) {
                    $('#orderstartpick').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/drops", function (drops) {
                drops.forEach(function (item) {
                    $('#orderstartdrop').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            $.getJSON("/orders/orderlist/priorities", function (priorities) {
                priorities.forEach(function (item) {
                    $('#orderstartpriority').append('<option value="' + item + '">' + item + '</option>');
                });
            });

            // shows the partial form
            $.getJSON("/orders/orderlist/conn", function (conn) {
                if (conn == "true") {
                    $('#orderstartmodal').modal('show'); //{ backdrop: 'static', keyboard: false, show: true });
                }
                else {
                    $('#noorderstartmodal').modal('show');  //{ backdrop: 'static', keyboard: false, show: true });
                }
            });

            // set focus on the pick input on form load - Not working on load
            $('#orderstartmodal').on('shown.bs.model', function () {
                $('#orderstartpick').focus();
            });

            // Hide the submit button by class name on form load - Not working on load
            $('#orderstartmodal').on('shown.bs.model', function () {
                $('#submitbtn').hide();
            });

            // Set focus on the drop 
    input after the pick input has 
    changed - Working
            $('#orderstartpick').change(function () {
                $('#orderstartdrop').focus();
            });
           

        });

Partial form code in my .cshtml page

<div id="orderstartmodal" class="modal fade" tabindex="-1" role="dialog">
    <form method="post" asp-page-handler="orderstart">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header" style="background-color:blanchedalmond">
                    <h5 class="modal-title font-italic" id="orderstartmodaltitle" value="">START ORDER</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" style="background-color:burlywood">
                    <table class="table table-sm">
                        <tbody>
                            <tr>
                                <td align="right" width="50%">
                                    <div class="form-group">
                                        <label for="orderstartpick" class="col-form-label">Pick Stn.:</label>
                                        @*<select id="orderstartpick" name="orderpick" class="select-picker" style="width:60%"></select>*@
                                        <input type="text" autofocus="autofocus" id="**orderstartpick**" name="orderpick"  style="width:60%">
                                        @*<script type="text/javascript">document.getElementById('orderstartpick').focus();</script>*@
                                        @*<script>document.getElementById('orderstartpick').focus();</script>*@
                                       
                                        @* <script type="text/javascript">
                                        $(document).ready(function () {
                                            $(function () {
                                                    $('#orderstartpick').focus();
                                            });
                                        });
                                        </script>*@

                                    </div>
                                </td>
                                <td align="right" width="50%">
                                    <div class="form-group">
                                        <label for="orderstartdrop" class="col-form-label">Drop Stn.:</label>
                                        @*<select id="orderstartdrop" name="orderdrop" class="select-picker" style="width:60%"></select>*@
                                        <input runat="server" type="text" id="**orderstartdrop**" name="orderdrop" style="width:60%">
                                    </div>
                                </td>
                            </tr>
                            <tr style="visibility:collapse">
                                <td align="right" width="50%">
                                    <div class="form-group">
                                        <label  hidden="hidden"  for="orderstartpriority" class="col-form-label">Priority:</label>
                                        <select hidden="hidden"  id="orderstartpriority" name="orderpriority" class="select-picker" style="width:60%"></select>
                                    </div>
                                </td>
                                <td width="50%">
                                    <div hidden="hidden" class="form-group">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="center" valign="middle" colspan="2">
                                    <div class="form-group">
                                        <label for="orderstartinfo" class="col-form-label">Select/Verify Parameters And Then Click:</label>
                                    </div>
                                    <div class="form-group">
                                        <button runat="server" type="submit" class="btn btn-primary">START ORDER</button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer" style="background-color:blanchedalmond">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </form>
</div>

I tried HTML code for focus, Fava code, and razor code, but not of the things tried to set focus to input one.


Solution

  • Update:

         // shows the partial form
                    $.getJSON("/orders/orderlist/conn", function (conn) {
                        if (conn == "true") {
                            $('#orderstartmodal').modal('show');
                            $('#orderstartmodal').on('shown.bs.modal', function () {
                                 $('#orderstartpick').focus();
                              })
                        }
                        else {
                            $('#noorderstartmodal').modal('show');  //{ backdrop: 'static', keyboard: false, show: true });
                        }
                    });
    

    Note: As you can see, within your code snippet I can see a if conditional while loading the modal. You should please below code sippet on load just after loading the modal:

    $('#orderstartmodal').on('shown.bs.modal', function () {
                $('#orderstartpick').focus();
            })
    

    I tried HTML code for focus, Java code, and razor code, but not of the things tried to set focus to input one.

    Well, in this scenario, you have to write your focus script inside your main view not in parttial page of course. You can do something like below:

    Script For Input Focus:

        $(document).ready(function () {
            $(function () {
                $('#orderstartmodal').modal('show');
    
            });
            $('#orderstartmodal').on('shown.bs.modal', function () {
                $('#orderstartpick').focus();
            })
         
            $("#orderstartpick").change(function () {
                $('#orderstartdrop').focus();
            });
                
     });
    

    Note: This script need to placed below your main page where you have called your partial view. As you can see I have used change and onmouseover both would perform. However, as per your description, you need on change event then set your focus to next input box that is: $('#orderstartdrop').focus();

    Output:

    enter image description here

    Note: As you haven't shared your main page details, so I have just loaded below another page.