Search code examples
javascripthtmljqueryhtml-input

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 3 in this input field, I want the value of the field to be 0.3
  • When, after that, I input a 5, I want the value to become 3.5
  • ... then a 9, the value should become 35.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' />


Solution

  • Change opacity from .3 to 0 when happy. You may want to suppress decimals

    $('#hidden-tenths').on('input', function(e) {
      $('#input-tenths').val((this.value/10).toFixed(1))
    });
    #input-tenths { opacity:1; position:absolute; z-index:0; }
    #hidden-tenths { opacity:.3; position:absolute; z-index:100; }
    <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' />