Using Javascript to focus on the value of a textfield

Criteria: Please only use Internet Explorer for testing purposes

Requirements: There is an alert message in place to check if a user enters a value with less than 8 digits - the user should not be able to proceed to the next field and must remain on the current field.

Challenge: The functionality works well, however, there is one issue - when a user enters a value in a text field with less than 8 digits, the focus returns in a way that moves the cursor to the first letter of the entered value instead of going back to the last letter of the value.

Sample Code:

<html>
<body>
<script>
function validateField(field) {

        if (field.value.length < 8) {
            // Toggle the active element's blur off and back on after the next blur
            var active = document.activeElement;
            if (active && active !== field) {
                var blur = active.onblur || function(){};
                active.onblur = function(){ active.onblur = blur };
            }
            field.focus();
            alert("Value cannot be less than 8 digits");
        } 
    }

</script>
<input type="text" id="test1" onblur='return validateField(this);'> 
<br/>
<input type="text" id="test2" onblur='return validateField(this);'>
</tr>
</table>
</body>
</html>

Answer №1

This might seem like a workaround, but it actually does the trick - simply attach an onfocus listener to update the value with itself, and Internet Explorer will cooperate by placing the cursor at the end -

onfocus="this.value = this.value;"
:

Here's how you can use it:

<input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" />

If you're considering transitioning to JQuery (which I highly recommend), take a look at this plugin:

// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Moves the cursor to the end of a textbox or textarea

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function is available...
        if (this.setSelectionRange)
        {
        // ... then utilize it
        // (Not compatible with IE)

        // Double the length to accommodate Opera's inconsistency regarding carriage returns being one or two characters. Ugh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise, replace the content with itself
        // (Not effective in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom for tall textareas
        // (Essential for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);

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

Runtime Error: Invalid source property detected - Firebase and Next.js collaboration issue

Currently, I am developing a Next.js application that retrieves data from a Firestore database. The database connection has been successfully established, and the data is populating the app. However, I am facing an issue with displaying the image {marketpl ...

Is it possible to hide a div using Media Queries until the screen size becomes small enough?

Whenever the screen size shrinks, my navbar sections start getting closer together until they eventually disappear. I've implemented a button for a dropdown menu to replace the navbar links, but I can't seem to make it visible only on screens wit ...

What is the best way to have the slide shift to the left solely after the initial click and prevent it from moving left on subsequent clicks?

Is there a way to prevent the slide area from scrolling left when the left button is clicked before it has been scrolled right first? Additionally, how can we lock the scroll after it reaches the last div? var $slider = $("#recent-container") $("#right ...

Having trouble with Jest and React IntersectionObserver mock not functioning properly?

While working on my component.test.js file, I attempted to mock the IntersectionObserver using the following code: const mock = ()=>({ observe: jest.fn(), disconnect: jest.fn() }); window.IntersectionObserver = jest.fn().mockImplementation(mock) ...

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

Add a jQuery script to the admin panel of a custom WordPress plugin for sending emails through ajax

I've been working on integrating a form into an admin page on WordPress. The goal is to allow users to input their email address and trigger an email to be sent to that address. To achieve this, I'm utilizing a jQuery Ajax function to transmit th ...

An effective way to verify if a record has been successfully updated is by utilizing Sequelize's

Within this snippet of code, I made an update to a specific record in the IPAdress model. What is the best way for me to verify if the record has been successfully updated or not? let IPAdress = await model.IPAdress.update(data,{ where: { id } }); ...

Ways to create a border button with a matching width to the text above using CSS

Is it possible to style a border button in CSS so that the width matches the text above? I am trying to achieve a clean look for the navigation selected text, where the border-bottom aligns with the text above. Here is an example of what I have attempted ...

What is the reason behind the appearance of 'Cannot Get/' when trying to render pug?

Attempting to configure a basic Express server with a simple pug template. Could you kindly point out what I might be doing incorrectly in this setup? 'use strict'; //Require Express var express = require('express'); var app = expres ...

When hovering over CSS cards, they transform into a zigzag pattern and the text spills out of the box with overflow

I'm having an issue with my webpage where the text on my CSS cards is overflowing and not staying within the card. Additionally, when I hover over an element, the remaining CSS cards are arranged in a zig-zag manner. Here's the code snippet for r ...

What role does the conditional statement play in the function ExtrudeGeometry.UVGenerator.generateSideWallUV within three.js?

Within three.js's ExtrudeGeometry.UVGenerator.generateSideWallUV function, there is a specific condition being checked: if ( Math.abs( a.y - b.y ) < 0.01 ) { return [ new Vector2( a.x, 1 - a.z ), new Vector2( b.x, ...

Unable to access frame: Error - Unable to retrieve 'add' property from undefined

I am working on customizing the chatbot functionality for my website built with Nuxt.js. I want the chatbot to display on certain pages while remaining hidden on others. Unfortunately, I encountered an issue when trying to hide it on specific pages. To im ...

Scaling down the screen for a smaller display

Having trouble achieving a specific effect and could use some assistance. My goal is to create an action where, upon clicking on the nav element (for simplicity, I've set it to be triggered by clicking anywhere on the body), the following should occur ...

Modifying icons with JavaScript

When I click on the play icon, it changes to the pause icon. However, I am only able to change the first icon from play to pause in my JavaScript code. How can I apply this functionality to all the audio elements on the page? let playIcon = "https://ima ...

Stop a single piece of data from continuously cycling

<?php include ("config.php"); $results = $mysqli->query (" SELECT orders_history.transaction_id, orders_history.items, orders_history.quantity, orders_history.on ...

Dynamically adjust the image link in responsive mode to improve user experience

Is there a way to dynamically change the image links in responsive mode on WordPress? I am displaying thumbnails with a fixed size of 280*200, but I want to switch to medium-sized thumbnails (480*200) when the resolution is between 480px to 600px. Is there ...

Applying CSS Styles to a Single Class Only

I have been using Zurb's Foundation to customize the navbar with my own styles, which has been successful so far. However, I encountered an issue with the responsive behavior of the navbar when the viewing container size changes. The navbar adds a sec ...

Confusion between modules and classes in Node.js when using CoffeeScript

I'm struggling to understand how to use Protoype in CoffeeScript, even though I am familiar with using it in standard Javascript with Node.js and modules. Imagine I have a file named mymodule.coffee: Module = {} class MyModule constructor: (para ...

validating schemas with yup - checking tuples and alternative data structures

I searched through yup's documentation but couldn't find any information on validating tuple arrays and alternative objects. Can someone provide guidance on how to validate an object with these specific properties using yup? interface Example { ...

When utilizing a question mark in a string, there is a discrepancy between the encoding in asp.net server and URL encoding

When encoding a string in ASP.NET, I use the function Server.UrlEncode(GAE?), which results in the string GAE%3f. However, when using the JavaScript function encodeURIComponent(GAE?), the result is GAE%3F. Unfortunately, the validation of the string fail ...