Enter with type = number, but add an alphabetical suffix
I have <input type="number"></input>
. I like the fact that it has type="number"
, since I want to receive numeric input from the user. I would prefer not to change its type from number. However, I would like to display the units after the number. So I want the input to read "5 px" if the device is in pixels. I want the user to be able to edit 5 part but not the px part. The solution found here won't work unless I do more tricks and make it a hacker, because "px" will appear after the up / down arrows in chrome. These are the arrows I'm talking about! [Example of arrows] [1]
In my environment in chrome you can just put alphabetic characters in <input ...>
, but this is technically not legal
I need a solution that works on firefox, chrome, safari and IE9.
source to share
Just to throw it in there is how I was going to approach this before asking this question. I was going to make an additional, identical one <input>
, but not make it type="number"
and make it position: absolute
. Thus, it will add up directly below the actual one <input ...>
. Then I would set it to "px", putting a space for each digit in the other input. As long as you use a monospaced font, "px" should be placed correctly. Browsers may end up overlapping it with arrows or something, who knows though.
Edit: I ended up doing absolutely positioned <label>
, if you set a property for
as the id of your input, then when you click on <label>
it will focus the input and be ready for keystrokes. Then you just change the css value of the label cursor: text
so that when you hover over the label, the correct cursor is set. I've tested this on IE9 +, FF, Safari and Chrome.
source to share
You can achieve this using the following HTML:
<div class="size-input-wrapper">
<label for="inputValidation">Enter size:</label>
<input type="number" id="inputValidation" placeholder="size"/>
<span class="pxSpan">px</span>
</div>
CSS
.size-input-wrapper {
max-width: 208px;
margin: auto;
position: relative;
display: inline-block;
}
#inputValidation {
padding-right: 35px;
}
.pxSpan {
position: absolute;
top: 19px;
right: 10px;
}
Alternatively, you can use bootstrap for a simpler implementation. Check FIDDLE
source to share