'How to make an HTML number input that transforms its value to tenths (possibly using jQuery)
Let's say I have an input field like
<input type='number' id='input-tenths' />
What I want to achieve in this, is the digits I put into this field being treated as "tenths" instead of whole numbers, for example:
- When I input a
3in this input field, I want the value of the field to be0.3 - When, after that, I input a
5, I want the value to become3.5 - ... then a
9, the value should become35.9
I have so far tried to add a hidden field <input type='hidden' id='hidden-tenths'/>, and a function like
$('#input-tenths').on('input', function(e){
$('#hidden-tenths').val($('#hidden-tenths').val() + '' + $(this).val().slice(-1));
$(this).val($('#hidden-tenths').val() / 10);
$('#hidden-tenths').val($(this).val() * 10);
});
but this doesn't always work as expected (for example, when I backspace in the original input, a digit is appended rather than removed, as can be expected from using the .slice(-1).
What would be a good way to achieve the expected behaviour, where I'm trying to stay away from explicitly binding all key presses and thereby essentially reprogramming the input field (except when this is the only way to achieve this).
$('#input-tenths').on('input', function(e) {
$('#hidden-tenths').val($('#hidden-tenths').val() + '' + $(this).val().slice(-1));
$(this).val($('#hidden-tenths').val() / 10);
$('#hidden-tenths').val($(this).val() * 10);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id='input-tenths' />
<input type='number' id='hidden-tenths' />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
