Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add text to the input after the entered value

When you type something into the input I want it to always add " h" at the end (h – hours).
When you enter "21", the input value should be "21 h". When you enter "37", the input value should be "37 h", etc.

<input type="text" class="input">
$(".input").on('input', function(){
  let input = $(this).val();
  $(this).val(input + " h");
})

The code above gives "2 h1 h" when you enter "21". How can I add " h" at the end of the whole value instead of adding it to every entered character?
(I can’t add <p> tag after the input)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you know you will only have number inputs, you can use the following to remove all characters that aren’t digits.

$(".input").on('input', function(){
    let input = $(this).val();

    input = input.replace(/[^0-9]/g, '').trim();

    $(this).val(input + " h");
})

Backspace event:

$(".input").on('keyup', function(e) {
    if (e.keyCode == 8) {
        let input = $(this).val();
        input = input.replace(/[^0-9]/g, '').trim();
        input = input.substring(0, input.length - 1);
        $(this).val(input + " h");
    }
});

You can extract the logic to a new function called getInput for better code readability and management.

const getInput = (input, del) => {
    input = input.replace(/[^0-9]/g, '').trim();

    if (del) input = input.substring(0, input.length - 1);

    return `${input} h`;
}

$(".input").on('input', () => $(this).val(getInput($(this).val())))

$(".input").on('keyup', () => {
    if (e.keyCode === 8) $(this).val(getInput($(this).val(), true));
});

If you want a CSS solution, please refer to this answer https://stackoverflow.com/a/49797347/6895166

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading