Arthur Robaeys
Arthur Robaeys

Reputation: 355

How to add text unit (e.g. cm) inside input tag?

I'm looking to put a measurement unit in my input, but I don't know how. I want something like this:

[............ cm]

This is my html:

    <div class="input">
     <label for="height">Height</label>
     <input id="height" type="text" value="" name="height">
    </div>

If I try to add a span next to the input, it just places it outside the input.

Upvotes: 1

Views: 4856

Answers (2)

user12915445
user12915445

Reputation:

The easiest way would be to add a square after the input field, you can do that manually using ::after on CSS but one of the easiest ways is to use frameworks like bootstrap. You can find below a template from their website. You can also read more of this here: https://getbootstrap.com/docs/4.0/components/input-group/

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="measurement" aria-label="measurement" aria-describedby="basic-addon2">
  <div class="input-group-append">
    <span class="input-group-text" id="basic-addon2">cm</span>
  </div>
</div>

Upvotes: 1

Reza Saadati
Reza Saadati

Reputation: 5419

If you would like to set cm at the end of your value, you could try to change the value with JavaScript.

Here is an example of how you could do it:

document.getElementById('number').addEventListener('keyup', (e) => {
	e.target.value = e.target.value.split('cm').join('');

	if (e.target.value.slice(-2) !== 'cm') {
  	e.target.value = `${e.target.value}cm`;
  }
});
input {
  text-align: right;
}
<input type="text" id="number" value="cm">

But anyway, that's not the best solution. I would recommend using placeholders, labels or maybe a tooltip to let the user know what kind of unit the input is about.

Upvotes: 1

Related Questions