"If the user presses the backspace key on the keyboard, jQuery will automatically navigate to the previous input

I'm currently working with a jQuery script:

$(document).ready(function() {
    //Focus the first field on page load
    $(':input:enabled:visible:first').focus();
    //Clear all fields on page load
    $(':input').each(function() {
        this.value = "";
    });
});
//Clear field on focus
$('input').focus(function() {
    this.value = "";
});
//Allow only alphabetical characters in the fields
$(':input').bind("keypress", function(event) {
    if (event.charCode != 0) {
        var regex = new RegExp("^[a-zA-Z]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
        $(this).next('input').focus();
    }
});
//Enumerate submit click on [ENTER]-keypress
$(':input').keypress(function(e) {
    if (e.which == 13) {
        jQuery(this).blur();
        jQuery('#submit').click();
    }
});
//Submit form
$('#submit').click(function() {
    //Show loading image while script is running
    $("#response").html("<img src='../images/loader.gif'>");

    //POST fields as array
    function serealizeInputs(input) {
        var array = [];
        input.each(function() {
            array.push($(this).val())
        });
        return array;
    }

    var letters = serealizeInputs($('.letters'));

    $.post('loadwords.php', {
        letters: letters
    }, function(data) {
        //Show the response from loadwords.php
        $("#response").html(data);
    });
});

Check out the code here: http://jsfiddle.net/8S2x3/1/

I'm looking to improve its efficiency, but not sure where to start.

Most of the code I've used is a result of copying and modifying existing code, as I am still learning.

Now, my questions are: 1. How can I move focus to the previous textfield on a Backspace keypress? I want users to be able to erase a character if they mistype, and then automatically move the focus to the previous input field by pressing backspace again. 2. Also, I'm curious about how to add a CSS class when a field has a value, and add another CSS class when it's empty.

Answer №1

Give this a shot:

$(':input').keydown(function(e) {
    if ((e.which == 8 || e.which == 46) && $(this).val() =='') {
        $(this).prev('input').focus();
    }
});

JSFiddle Link

Answer №2

Here is a suggestion to try:

$(':input').keydown(function(e)
{
    if($(this).val() =='' && e.which ==8)
    {
        alert("Alert triggered when backspace key pressed with empty input field");
    }        
});

Answer №3

If you're looking for a handy solution to populate a group of four input fields, each restricted to just one character, whether it's for a competition entry, a login form, or even confirming attendance at a meeting, then this is the perfect guide for you:

  1. Simply click on the input field to automatically highlight all text.
  2. Enter a single character in each input field, and watch as the cursor smoothly moves to the next one.
  3. If you need to delete a character, don't worry – the cursor will smartly jump back to the previous input field.

For a visual representation, check out the image here.

To implement this functionality in your HTML code, use the following structure:

<div class="code">
    <input type="text" name="code1" maxlength="1" />
    <input type="text" name="code2" maxlength="1" />
    <input type="text" name="code3" maxlength="1" />
    <input type="text" name="code4" maxlength="1" />
</div>

And here's how you can achieve this behavior using jQuery:

$(":input").on("focus",function(e){
    $(this).select();
});
$(":input").on("mouseup",function(e){
    $(this).select();
    return false;
});
$(':input').keyup(function(e) {
    if (e.which == 8 || e.which == 46) {
        $(this).prev('input').focus();
    }
    else {
        $(this).next('input').focus();
    }
});

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

Applying flexbox to create a visually appealing design

Is there a way to achieve this layout using flexbox without relying on grid due to limited support in IE11? I want to be able to easily add or remove small divs without adding more containers. To see the desired layout, check out this image: Desired Layou ...

Differences in color rendering between XAML WPF and HTML

After migrating my app from WPF to HTML, CSS, and JavaScript, I noticed a discrepancy in color representation. Despite using the same hex value, the HTML color appears lighter than in WPF. See the comparison image here: https://i.sstatic.net/vB7rR.png In ...

Dropdown menu not appearing in specific containers when using HTML

I am creating a navigation menu that includes a dropdown link labeled "More." <a href="#"><div class="indiv_nav_button"><p class="font_18 white">Children</p></div></a> ...

Creation of a Joomla module

I'm currently working on a simple module using jQuery, however I am facing issues with disabling MooTools. In my attempt to resolve this, I utilized the following code in the default.php file: $user =& JFactory::getUser(); if ($user->get( ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

Can a CSS Grid layout be achieved without prior knowledge of image sizes?

I am working on a project where I am pulling images from Reddit and aiming to showcase them in a gallery-style grid. I have tried using a flex display and resizing the images to match dimensions, but unfortunately not all images have the same dimensions ...

There appears to be some additional bottom padding in the text on React Native for

Having trouble aligning my two text components to the baseline on Android. I've tried using includeFontPadding: false, which worked for the top spacing but not for the bottom. Can anyone assist me with this issue? Check out the problem in this snack: ...

What could be the reason my Bootstrap webpage is not optimized for mobile devices?

My website is currently hosted at "nateshmbhat.github.io". I have implemented mdboostrp's row and col for the structure of my website, but unfortunately, it is not very mobile-friendly as it displays a lot of unnecessary background space. If you woul ...

Appending a row to a table will not trigger events in Select2

Despite several attempts, I can't seem to get the select2:select event working on dynamically added rows in a table using select2. The event only works on the original row. Unfortunately, I don't have any additional details about this issue. COD ...

Can a different div or HTML element be used in place of the text "Hello World"?

<body onload="myfunction('target')"><div id="target"> "Hey there!" </div></body> Can we replace the text "Hey there!" with another HTML element or div? This is currently a left-to-right marquee text. <script language= ...

an li element is accompanied by a visible box

In my possession is a container: #box1 { height:100px; width:208px; } along with a series <li id="first"><strong>FIRST</strong> </li> <li id="second"><strong>SECOND</strong&g ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Opening external stylesheets in a separate window

Objective: Create a new window, add elements to it, and then apply CSS styles to the elements in the new window using an external style sheet. Issue: While I am able to add elements to the new window and link it to an external style sheet in the head sect ...

Achieving the perfect background image size using Tailwindcss

Looking for a way to use an image with a height of 300px and a width of 1600px as a background in a div element? Although the div element's height can be extended beyond 300px, it results in an empty space at the top while covering the width. The de ...

Having trouble with jQuery AJAX - page continually refreshes upon submitting and data isn't being transmitted

I've been working on creating a dynamic AJAX function using PHP and MySQL to update database records without the need for page refresh or navigation. However, I haven't had much success with it yet. Here's the code I have on the page with t ...

Issue encountered when validating password through submission rate limiting

On my login page, I perform validation on the Email and Password entered by the user using submission throttling from the database. However, I encountered an error stating 'undefined index: txtMail' on the validate page. To track the server-side ...

Is it possible to AJAX call a file every X minutes until a specific time?

Here's the code snippet I'm working with: $(document).ready(function() { $.ajaxSetup({ cache: false }); // To address an IE bug. Prevents IE from loading only the first number and not refreshing setInterval(function() { $('# ...

Using navigator.app.backHistory to navigate back within the app

Currently working on Cordova for Android, incorporating jQuery and jQuery Mobile into my Example App. A slide menu is a key feature of the app, and I am using the "menubutton" event to toggle its visibility based on the global_isOpen variable: document.ad ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

At what point in the process does Angular/PrimeNG switch the CSS classes from 'p-' to 'ui-'?

So I've encountered quite a peculiar problem. I've managed to create a customized PrimeNG component that seems to be functioning properly, but there are a couple of issues at hand: Despite using ViewEncapsulation.None, just like with other Pri ...