Navigating between controls in a Listview with JavaScript

I have implemented a Javascript function to enable the use of arrow keys for navigating through 4 textboxes within an ASP Listview. While I can successfully move from Textbox1 to Textbox4 using the left arrow key, I am encountering an issue where I cannot navigate back from Textbox4 to Textbox1 using the right arrow key. Please refer to the image below for a visual representation.

4 Textbox's

<script type="text/javascript">
    $('input[type="text"],textarea').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

        if (key == 39) {
            e.preventDefault();
            var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');

            inputs.eq(inputs.index(this) + 1).focus();
            inputs.eq(inputs.index(this) + 1).click();
        }

        if (key == 37) {
            e.preventDefault();
            var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');

            inputs.eq(inputs.index(this) - 1).focus();
            inputs.eq(inputs.index(this) - 1).click();
        }
    });
</script>

Answer №1

To enhance user experience with the 4 TextBoxes, consider wrapping them in a container element and binding the left and right clicks to those elements' TextBoxes. Then utilize jQuery's prevAll and nextAll functions.

<div id="4TextBox">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</div>

<script type="text/javascript">
    $('#4TextBox input[type="text"]').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

        if (key == 39) {
            e.preventDefault();
            $(this).nextAll('input[type="text"]').first().focus();
        }

        if (key == 37) {
            e.preventDefault();
            $(this).prevAll('input[type="text"]').first().focus();
        }
    });
</script>

It is important to note that this method primarily works when the TextBoxes are adjacent to each other. If you have a different HTML structure where TextBoxes are enclosed within another element, such as shown below, adjustments may be required to ensure proper functionality.

<div id="4TextBox">
    <asp:TextBox ID="TextBox1a" runat="server"></asp:TextBox>      
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <p><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></p>
    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing issues with the POST method in my RESTAPI in node.js and it is not functioning

I recently started learning Node.js and Express.js with the goal of creating a basic API to retrieve data from a JSON file using the GET method, and to add a new user using the POST method. The GET method is functioning correctly, but I have encountered a ...

Can you explain the exact purpose of npm install --legacy-peer-deps? When would it be advisable to use this command, and what are some potential scenarios where it

Encountered a new error today: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1cfc4d9d5d5d6c8cfe1918f908f91">[em ...

Using Node.js and the Jade templating engine, display the value of a passed variable

Asking such a basic question makes me feel guilty. app.get('/skumanagement/:id', function (req, res){ var options = req.params.id; // req.params.id = itemidx database.skuGetDetail(options, function (error, data){ winston.log('inf ...

Expand the div width to the specified measurement horizontally

Is there a way to horizontally collapse a div (container) to a specific width that I can adjust, effectively hiding its content? The collapse effect should move towards the left. <div id="container"> <button type="button" id="myButton"> ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Retrieving innerHTML from a VueJS custom component

Attempting to create a basic bootstrap alert component, I am struggling to access the innerHTML of my custom component. Here is the code snippet: Vue.component('my-alert', { template: '#vue-alert', props: ['type', ' ...

Refreshing the page in VueJs does not trigger the axios function

I've encountered an issue with my VueJs app after purchasing the Vuexy template from ThemeForest. I created a new component called CountryTable.vue, and while it works initially, it fails to display data when I refresh the page. It only shows data whe ...

Show XDocument on a MasterPage

I am currently facing an issue with displaying an XDocument on a MasterPage that I have created using asp.net in C#. Despite dynamically creating the XDocument and using Response.Write to show it on the webpage, it seems to overwrite my MasterPage. I am st ...

Can the submit ID value be utilized in PHP?

name="submit" functions as expected. if(isset($_POST["submit"])) <input type="submit" ID="asdf" name="submit" value="Save" class="ui blue mini button"> I want to change it to use ...

Transfer an array via Ajax to a Python server script

I need to send the names, values, and labels of my form elements when a button is clicked. Since the submit button messes up the order, I decided to handle it with JavaScript: $('#mybutton').click(function() { m.modal('show'); ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Refreshing React when manually updating data in a variable within its respective file

One example in data.js is export const x={value:0}; Within app.js : import { x } from "./data"; function App() { return ( <div> {console.log("Re-render")} {x.value} </div> ); } export default App ...

Removing characters from a C# string that fall between two specified characters

As an illustration, let's consider a string such as: "//DeleteFromHere <div> <p>my name is John I want to delete this div </p> </div> //DeleteToHere" In this case, I intend to use //DeleteFromHere as the starting ...

Is it possible to send form data using the file upload function?

I've successfully implemented a file upload feature with a progress bar, and the file gets uploaded in fileUpload.php. function fileSelected() { var file = document.getElementById('fileToUpload').files[0]; if (file) { var fil ...

Retrieve all entries in MongoDB using Mongoose where a particular date falls within a specified date range

Consider a scenario where documents contain the fields: startDate: 2021-04-14T22:00:00.000+00:00 endDate: 2021-04-19T22:00:00.000+00:00 You want to retrieve all documents where a specific date (e.g., today) falls within the date range. Is it possible to c ...

Execute Yarn commands from the main directory

In the midst of my project, I have various sub projects - one of which is dedicated to JavaScript. My intention is to employ this JavaScript project as a task runner for the entire endeavor using gulp. However, I've hit a snag in the process. The lay ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

Managing redirection across multiple projects within a single solution

Within my C# Web Application, there are two distinct projects ("Project1" and "Project2") housed within a single solution. In "Project1," I've developed a webpage featuring a button that, upon clicking, triggers an OnClick event meant to store a sessi ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...