Home > Enterprise >  How to add text to the input after the entered value
How to add text to the input after the entered value

Time:10-16

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" >
$(".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)

CodePudding user response:

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

  • Related