JavaScript function issue with automatic tabbing

Encountered an issue while utilizing this in our asp.net application.

The main goal is as follows:

  • When in a textbox -> tab once MaxLength is reached
  • When in a checkbox -> tab once the control is toggled with the keyboard (spacebar)

Other than buttons, these are the only controls on the form. The functionality is toggled by the end user (saved using a cookie).

Challenges:

  • It seems to go through the process quite randomly. Sometimes it performs quickly, sometimes it doesn't. The form is currently set with a large tab index range that will likely remain. Not a major concern, but any tips would be appreciated.

  • The checkbox functionality is behaving oddly. For instance, when toggling CheckBoxA using the keyboard, it appears disabled and then focuses on CheckBoxB. Clicking anywhere on the page after this toggles CheckBoxA continuously, ignoring normal mouse actions until a right-click and dialog dismisses the context menu which is not ideal. This erratic behavior also affects CheckBoxB.

The important code for the function is provided below. CheckCookie() ensures that AutoTab is set before proceeding. Array.contains checks if the entered keycode is present in the array.

function test(input, inputClientID, e) {
// Code here 
}

Tabbing is managed using a sort function presented below:

function tabNextCtrl(input) {
// Code here
}

Apologies for the length, but any help with this issue would be greatly appreciated.

Thank you,

Answer №1

After making some adjustments, we finally found a solution that met our requirements. The use of tabindex was a bit unpredictable, but we managed to make it work.

Here is the JavaScript code:

function Tab(currentField, e) {
    if (!(e.keyCode == 9 & e.shiftKey)) {
        if (currentField.value.length == currentField.maxLength) {
            if (e.keyCode != 16 & e.keyCode != 9) {
                tabNextCtrl(currentField);
            }
        }

        if (currentField.type == "checkbox") {
            tabNextCtrl(currentField);
        }
    }
}

function tabNextCtrl(input) {
    var tbIndex = input; 
    var aIndex = 99999999;
    for (i = 0; i < input.form.elements.length; i++) {
        if ((input.form.elements[i].tabIndex > input.tabIndex) && 
            (input.form.elements[i].tabIndex < aIndex)) {
            aIndex = input.form.elements[i].tabIndex; 
            tbIndex = input.form.elements[i];
        }
    }
    tbIndex.focus(); 
} 

Demonstration of the CodeBehind:

protected void Page_Load(object sender, EventArgs e)
    {
        this.CheckBox1.Attributes["onclick"] = "Tab(this, event)";
        this.CheckBox2.Attributes["onclick"] = "Tab(this, event)";
        this.TextBox1.Attributes["onkeyup"] = "Tab(this, event)";
    }

Demonstration of the ASPX code:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script language="javascript" src="Scripts/autotab.js" type="text/javascript"></script>
<asp:CheckBox ID="CheckBox1" runat="server" TabIndex="1" Text="First" />
<br />
<asp:CheckBox ID="CheckBox2" runat="server" TabIndex="2" Text="Second" />
<br />
<asp:TextBox ID="TextBox1" runat="server" TabIndex="3" MaxLength="4" Width="4em" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" TabIndex="4" Text="Last" />

Answer №2


function HandleTab(currentElement, e) {

    if (!(e.keyCode == 9 || e.keyCode == 39)) {
        if (currentElement.value.length == currentElement.maxLength) {
            $(currentElement).next('input').focus();
        }
    }
    else {
        if (currentElement.value.length == 0) {
            $(currentElement).prev('input').focus();
        }
    }

}

<input name="code" id="code" class="input25p" onkeyup='HandleTab(this, event)' maxlength="4" type="text' border="0" >
<input maxlength="4" class="input25p" name="code1" type="text" border="0" onkeyup='HandleTab(this, event)' >
<input class="input25p" name="code2" maxlength="4" type="text" border="0" onkeyup='HandleTab(this, event)' >

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

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

Loop through the JSON data and display any empty strings

I encountered an issue while trying to convert an object string from a list of arrays using the JSON.parse method. Despite successfully converting the object string to an object, it appears empty when used within ng-repeat. Jade .item.col-md-4(ng-repeat= ...

Error encountered while attempting to import external JSON data into SurveyJS

This Codepen example showcases SurveyJS using a simple JSON structure: var json = { "questions": [{ "type": "text", "title": "Test question 1", "name": "Test question" }, { "type": "comme ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

Is there a way to determine if jQuery Mobile has already been loaded?

I am dynamically loading jqm and I'm trying to determine if it has been previously loaded in certain scenarios. Is there a method to check for the presence of jqm? ...

Tips for preventing useEffect from triggering a route?

Recently delving into reactjs, I stumbled upon a situation in the code where the route alerts messages twice. I'm seeking advice on how to prevent this issue, please disregard the redux code involved. Any suggestions? Index.js import React from &apos ...

How can I trigger a series of functions in sequence when a button is clicked using Vue.js?

When I click, I need to call 3 functions in a specific order: <CButton @click=" getBillPrice(); updateBill(); postData();" type="submit" color="primary">Save</CButton> However, the func ...

JavaScript can be used to append multiple array values within double brackets in Spring MVC

I am currently developing an application using Spring MVC with MongoDB. In the collection, I have retrieved multiple image name values: Ex: 1.jpg, 2.jpg, 3.jpg.... My Query: Now I need to place these values inside double brackets [[]] Ex : [["1.jpg"," ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

Determined Worth of Chosen <Datalist> Option

Currently, I am utilizing an <input type='text'> Element in conjunction with a <datalist> to suggest user names for a form. The functionality is working correctly and all my users are displayed. However, upon form submission, I need ...

Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from: The issue lies in pr ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

When ColorField is modified, the color of ScatterLineSeries in Telerik UI for ASP.NET AJAX remains unchanged

I am attempting to customize the color of a ScatterLineSeries in Telerik's RadHtmlChart, but I am facing difficulties as the markers and lines are always displayed with default colors. Despite rewriting my code in different styles, I have not been suc ...

Issue with Vue Checkbox not functioning properly upon being mounted in Edge browser

Currently, I am developing a Vue page with a checkbox that needs to read a value from a cookie upon mounting. However, I have observed that in the Edge browser, the checkbox does not get set correctly even though the Mounted function is definitely being ca ...

Using JavaScript to dynamically change the IDs of multiple select elements during runtime

I am facing an issue when trying to assign different IDs to multiple select elements at runtime. The number of select elements may vary, but I need each one to have a unique ID. Can anyone assist me in locating the select elements at runtime and assignin ...

Tips and tricks for activating javax.script in Websphere liberty profile on Bluemix

I am looking to incorporate JavaScript into one of my Java applications. In order to test this, I executed the following code: javax.script.ScriptEngineManager manager = new ScriptEngineManager(); javax.script.ScriptEngine engine = manager.getEngineByName ...

angular: handling duplicates in ng-repeat

Here is the JSON data: streams = [{ id: 0, codec_type: 'video', content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' }, { id: 1, codec_type: 'audio', content: '5.1(side) - cze - undefined' }, ...

What is the most effective approach to integrating socket.io as a submodule into the ExpressJS framework?

In my current project, I am working on developing an application using ExpressJs and following the submodule architecture recommended by tjholowaychuk. Furthermore, I also want to incorporate real-time socket interactions into the app by integrating socke ...

Troubleshooting: Why isn't my Ajax post functioning correctly with PHP variables?

After researching similar questions, I have discovered that in order to send a JavaScript value to a PHP variable, AJAX must be used. Here is what I have tried: function onCursorChanged(e, data) { $.post('familytree.php', {id: data.context.i ...