Ask Your Question
2

How to activate numeric keypad when an HTML/Javascript element is in focus?

asked 2022-08-24 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-04-27 04:00:00 +0000

scrum gravatar image

To activate the numeric keypad when an HTML/Javascript element is in focus, you can use the following code snippet:

<input type="number" onfocus="activateNumericKeypad()" />

<script>
function activateNumericKeypad() {
    var inputElement = document.activeElement;
    inputElement.setAttribute("pattern", "\d*");
    inputElement.setAttribute("inputmode", "numeric");
}
</script>

In the above example, the <input> element has the type="number" attribute set which will automatically show the numeric keypad on mobile devices. However, on desktop devices the user may need to manually enable the numeric keypad.

To automatically enable the numeric keypad when the <input> element is focused, we attach an onfocus event to the element that calls the activateNumericKeypad function. The function then retrieves the active element and sets the pattern and inputmode attributes to allow only numeric input.

Note: The inputmode attribute is relatively new and not all browsers support it. If the numeric keyboard is not showing with the code above, you may want to check if your browser supports the inputmode attribute or use a third party library to implement a custom numeric keyboard.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-24 11:00:00 +0000

Seen: 10 times

Last updated: Apr 27 '22