What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters?

HTML

<input type="number" name="cost" value="0.00" />

JavaScript

$.fn.setCursorPosition = function (pos) {
    this.each(function (index, elem) {
        if (elem.setSelectionRange) {
            elem.setSelectionRange(pos, pos);
        } else if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    });
    return this;
};

$('input[name=cost]').click(function() {
    $('input[name=cost]').setCursorPosition(55);
});


EDIT:

Upon further investigation, it appears that Chrome does not support this functionality with the number type. Is there a cross-browser workaround that doesn't involve changing the type to text?

EDIT 2:
After extensive research, it seems there is no solution to getting this to work with the number type. Why do browser manufacturers impose these limitations? Perhaps we should consider using pseudo-elements for all our elements just to challenge them, especially Google, and disrupt their precious search algorithm.

Answer №1

One possible solution is to adjust the input field by toggling the type attribute from text on keydown to number on keyup.

It may seem like a workaround, but it can effectively address the issue at hand.

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

What is the best way to find all the corners along a path?

I am working with an SVG path and I need to find all the extremum points (corners) on this path. How can I achieve this? I attempted to retrieve all points using the following code: let totalLength = path.getTotalLength(); for (var i = 0; i < totalL ...

Angular 2: Obtaining the caret position in a contenteditable 'div'

Take a look at this code snippet: <div #test (click)="onClick(test)" contenteditable="true"> This text can be edited by the user. </div> @ViewChild('test') el:ElementRef; constructor(private elementRef: ElementRef) {} ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Adjusting the size of a Vue component on the fly

I'm struggling to find a way to dynamically adjust the width of a component. The component I am working with is called 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu. To set the width, you need to assign a number to the prop ...

Having trouble getting Jquery Ajax Post to work properly when using JinJa Templating?

Objective: My goal is simple - to click a button and post information to a database. Problem: Unfortunately, clicking the button doesn't seem to be posting to the database as expected. Setup: I am working with Flask Framework, Jquery, and Jinja Temp ...

Triggering an event on a checkbox following an AJAX response

My website has 3 different categories, each with a dropdown menu containing various values with checkboxes. When a checkbox is checked, an AJAX request is triggered to fetch a response. The problem I'm facing is that the dropdown menus disappear afte ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

I attempted to connect my JavaScript file to my HTML file, but unfortunately, no changes are taking place

I have created an HTML file where I am trying to pass input from it into a function located in a separate JavaScript file, and then have the data added to a SQL server. The JavaScript file works perfectly fine when run independently, but when I try to call ...

What is causing my fetch response to not be passed through my dispatch function?

I'm currently utilizing a node server to act as the middleman between firebase and my react native app. Could someone kindly point out what might be going awry in my fetch method below? export const fetchPostsByNewest = () => { return (dispatch ...

The Angular ng-repeat directive is populating a list with items, but the parameters enclosed in double curly braces

After calling an API, the response contains data in the following format: [{name: "ABC", age: 20}, {name: "DEF", age: 25}] Even though the $scope.names variable is assigned with the array from the API, when viewed in the browser, it displays 2 rows but th ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...

Tips for effectively placing a page scope block using BEM

Here is the current structure of my header. The page component is assumed to be the root. Currently, the geometry of the social-links block is being controlled by the header__social-links mix (positioned absolutely relative to the header). How can I prop ...

Is there a way to postpone the action so that the bot will not acknowledge the second command until after I have completed the first command

client.on('message', async (message) => { let author = message.author.username if (message.author.bot) return; if (message.content.startsWith('-queue open ')) { message.content = message.content.replace('-queue o ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

Achieving centered positioning for the 'row' class in Foundation 5, regardless of browser size

While viewing on desktop, the body is centered which is ideal. However, resizing the browser causes it to stretch to fit the full width and I want to avoid this. Regardless of the browser size, I want the first div with the "row" class to be centered with ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Resizing SVG to specify width in pixels and automatically adjust height

I'm having trouble understanding how SVG works. Can someone explain where my mistake is? Here's an example of my inline SVG code: <div style="width:1000px; height:auto; background-color:blue;"> <svg class="_image"><use xlink ...

Guide on accessing text content from a sibling div element using jQuery

There are several divs arranged on a page as shown below. If a user clicks a link within the UL .list-links, I want to capture the content inside: <span class="asa_portlet_title">Title here</span> and store it in a variable. I have attempted ...