How to return down on a radzentextbox when the enter key is pressed

27 Views Asked by At

hello I have a blazor page that a RadzenCard with some fields in it I want to be able to return down a field when the enter button is clicked I have looked online and tried a few things but its not working

here is my code

@page "/"
@attribute [Authorize]
@using System.Text.Json;
@using Blazored.LocalStorage;
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject DialogService DialogService
@inject ContextMenuService ContextMenuService
@inject TooltipService TooltipService
@inject NotificationService NotificationService
@inject NavigationManager NavManager
@inject Blazored.LocalStorage.ILocalStorageService oLocalStore


<PageTitle>Form</PageTitle>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1 class="h3" style="display: block; text-align: center">Welcome Chris DeBrodie!</h1>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    @foreach (var (inputData, index) in inputCardData.Select((data, index) => (data, index)))
                    {
                        <div class="col-md-12">
                            @if (index == 0)
                            {
                                <!-- Render the dropdown only for the first card -->
                                <RadzenDropDown TValue="string" ValueProperty="BuildingName" TextProperty="BuildingName" Data="@buildingLists" @bind-Value="inputData.BuildingName" AllowSelectAll="false" Placeholder="School Name" Style="width: 100%; text-align: center" @onkeydown="@(e => HandleKeyDown(e, index))" />
                            }

                            <RadzenCard Variant="Radzen.Variant.Filled">
                                <div class="form-group">
                                    <RadzenTextBox TextProperty="CPSNumber" Data="@surplusItemsNews" @bind-Value="inputData.CPSNumber" Placeholder="CPS Number" Style="width: 100%; text-align: left" @onkeydown="@(e => HandleKeyDown(e, index))" @onchange="@(value => OnAutoCompleteChange(value, index))" @oninput="() => AddNewCard(index)" AutoComplete="false" />
                                </div>
                                <div class="form-group">
                                    <RadzenTextBox TextProperty="Description" Data="@surplusItemsNews" @bind-Value="inputData.Description" Placeholder="Item Description" Style="width: 100%" @onkeydown="@(e => HandleKeyDown(e, index))" @onchange="@(value => OnAutoCompleteChange(value, index))" />
                                </div>
                                <div class="form-group">
                                </div>
                                <RadzenDropDown TValue="string" ValueProperty="ReasonDescription" TextProperty="ReasonDescription" Data="@reasons" @bind-Value="inputData.ReasonDescription" Placeholder="Reason For Surplus" Style="width: 100%" @onkeydown="@(e => HandleKeyDown(e, index))" />
                            </RadzenCard>
                        </div>
                    }



                </div>
            </div>
        </div>
    </div>
</div>
<RadzenButton Style="width: 100%; min-width: 0px; min-height: 0px; height: 40px; display: block; background-color: #005570" Text="Review" Click="FinalizeList"></RadzenButton>



@code {
    [Inject]
    protected Surplus.WASPOService WASPOService { get; set; }
    string KeyPressed = "";
    protected System.Linq.IQueryable<Surplus.Models.WASPO.SurplusItemsNew> surplusItemsNews;
    protected System.Linq.IQueryable<Surplus.Models.WASPO.BuildingList> buildingLists;
    protected System.Linq.IQueryable<Surplus.Models.WASPO.Reason> reasons;




    // Create a class to hold form data
    public class FormData
    {
        public string BuildingName { get; set; }
        public string CPSNumber { get; set; }
        public string Description { get; set; }
        public string ReasonDescription { get; set; }
        public string SurplusSatus { get; set; }

    }





    // Inject the ILocalStorageService
    [Inject]
    private ILocalStorageService localStorage { get; set; }

    private productDtoVM product = new();


    // Create a list to store instances of the form data
    List<FormData> inputCardData;

    // Event handler for handling keydown event
    private async Task OnAutoCompleteChange(object value, int index)
    {
        var nextIndex = index + 1;
        if (nextIndex < inputCardData.Count)
        {
            // This selector might need adjustment based on your actual HTML structure
            var querySelector = $"input[rzinputtext]:nth-of-type({nextIndex + 1})";
            await JSRuntime.InvokeVoidAsync("setFocus", querySelector);
        }
    }

    // Adjust the HandleKeyDown method
    private async Task HandleKeyDown(KeyboardEventArgs e, int index)
    {
        if (e.Key == "Enter")
        {
            await JSRuntime.InvokeVoidAsync("event.preventDefault");
            var nextIndex = index + 1;
            if (nextIndex < inputCardData.Count)
            {
                // Assuming the next element is a text input. Adjust based on actual rendered elements.
                var querySelector = nextIndex == 0 ? "input[rzinputtext]" : $"input[rzinputtext]:nth-of-type({nextIndex + 1})";
                await JSRuntime.InvokeVoidAsync("setFocus", querySelector);
            }
        }
    }



    // Constructor to initialize inputCardData
    public Form()
    {
        inputCardData = new List<FormData>();
        // Add a default instance to the list
        inputCardData.Add(new FormData());
    }










    private int cardIdCounter = 1;

    [Inject]
    protected SecurityService Security { get; set; } // Counter for the card ID

    // Event handler for adding a new card when a ReasonDescription is selected
    private void AddNewCard(int index)
    {
        // Check if the current card is the last one in the list
        if (index == inputCardData.Count - 1)
        {
            // Add a new FormData instance without copying the BuildingName property
            inputCardData.Add(new FormData
                {
                    CPSNumber = inputCardData[index].CPSNumber,
                    Description = inputCardData[index].Description,
                    ReasonDescription = inputCardData[index].ReasonDescription

                });

            cardIdCounter++; // Increase the ID counter
        }
    }


    // Function to save inputCardData to local storage
    private async Task SaveInputCardDataToLocalStorage()
    {
        try
        {
            await localStorage.SetItemAsync("inputCardData", inputCardData);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error saving to local storage: {ex.Message}");
        }
    }

    // Function to load inputCardData from local storage
    private async Task LoadInputCardDataFromLocalStorage()
    {
        try
        {
            inputCardData = await localStorage.GetItemAsync<List<FormData>>("inputCardData");
            // Initialize the list if it's null
            if (inputCardData == null)
            {
                inputCardData = new List<FormData>();
                //Initialize list with Default instance of FormData when nothing is stored in local storage
                FormData defaultFormData = new FormData();
                inputCardData.Add(defaultFormData);

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading from local storage: {ex.Message}");
        }
    }

    protected override async Task OnInitializedAsync()
    {
        surplusItemsNews = await WASPOService.GetSurplusItemsNews();
        buildingLists = await WASPOService.GetBuildingLists();
        reasons = await WASPOService.GetReasons();

        // Load inputCardData from local storage when the page initializes
        await LoadInputCardDataFromLocalStorage();
    }

    // Event handler for the "Finalize List" button
    private async Task FinalizeList()
    {
        // Save the input card data to local storage
        await SaveInputCardDataToLocalStorage();

        // Navigate to the summary page
        NavManager.NavigateTo("/summary");
    }

    public productDtoVM inputData = new productDtoVM();

    [Inject]
    protected IJSRuntime JsRuntime { get; set; }

    public async Task HandleValidSubmit()
    {
    }
    public class productDtoVM
    {
        public string CPSNumber { get; set; }
        public string Description { get; set; }
        public string reason { get; set; }
    }

    public void keydown(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs args)
    {
        KeyPressed = "Key Pressed is " + args.Key;
        if (args.Key == "Enter")
        {
            JsRuntime.InvokeVoidAsync("onFocus", "CPSNumber");
        }
    }

}

here is my javascript code

window.onFocus = (id) => {
    var currInput = document.activeElement;
    if (currInput.tagName.toLowerCase() == "input") {
        var inputs = document.getElementsByTagName("input");
        var currInput = document.activeElement;
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i] == currInput) {
                var next = inputs[i + 1];
                if (next && next.focus) {
                    next.focus();
                }
                break;
            }
        }
    }
} 

I have done everything I can think of and still can't get the to return down when the enter button is pressed!!!

I am still new to blazor development so I am sorry in advance if this is a noob question

any help would be amazing!!!!!

thanks in advance!

0

There are 0 best solutions below