Home > front end >  Javascript function to automatically add a percent symbol when a number is entered into a text box?
Javascript function to automatically add a percent symbol when a number is entered into a text box?

Time:08-03

I'm working on a website that has a text box to enter a price discount, and I want a percent to automatically be added to the input when someone puts a number into the text box. I'm sure this is really easy, but I'm new to Javascript and I haven't been able to find anything on SO.

<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount" oninput="addPercent()">
</div>

Thanks!

CodePudding user response:

I would rather recommend you to have % as text next to the input field.

<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount" oninput="addPercent()">
<span >%</span>
</div>

If you still need to add it to the input field, I would recommend to add event listener on input blur.

You may need to have some extra validation as well for checking interger values of the input. Also, blur event fires once the focus is removed from the input. With keyup/keydown, there could be some chances that it will get into race condition if the user is typing values too fast in the input field.

document.getElementById('discount').addEventListener('blur', function() {
  this.value = this.value.replace('%','') '%'; //remove existing % and add again
});
<div>
<label for="discount">Enter discount</label>
<input type="text" name="discount" id="discount">
</div>

CodePudding user response:

Just adding a "%" to the end of a text in an <input> might be adequate but filtering an <input> to accept only numbers and dots and then add a "%" is far better:

Bind input event to <input>

document.querySelector('input').oninput = function(e) { //...

Get the current value of <input> .replace() whatever isn't a number or dot with nothing. Then add a "%" to the end of the value.

this.value = this.value.replace(/[^\d\.]/g, '')   '%';

Next, get the end position of value

let end = this.value.length;

Then make a selection range that goes from end position to one character length back.

this.setSelectionRange(end, end-1);

Finally, set .focus() so that the cursor will always be right before the "%"

this.focus()

Are you sure that you'd want a "%" in the actual value? If you intend to process that value then it'll be an extra step just to remove it for calculating percentages.

document.querySelector('input').oninput = function(e) {
  this.value = this.value.replace(/[^\d\.]/g, '')   '%';
  let end = this.value.length;
  this.setSelectionRange(end, end-1);
  this.focus();
}
<input>

  • Related