This question already has an answer here:
-
How can I add an unremovable prefix to an HTML input field?
15 answers
How do I generate an input element that has a default starting value in there that is unchangeable? For example, I am looking for a number from the user but I want '333' to be already in the input text box since all inputs will start with that number. I also don't want the user to be able to change it. I need the 333 to be part of the value also rather than just being added via style since I need to do validation on it.
I'd use 2 inputs as William B suggested but I'd consider whether to use the disabled
attribute or the readonly
attribute. The disabled
attribute won't allow the first input to be focused and the default browser styling will give it a gray background. The readonly
attribute will allow it to be focused and may have a more desirable initial styling.
One possibilty using JavaScript:
nine = document.getElementById("nine");
nine.addEventListener("keydown", function (ev) {
var el = this;
var value = el.value;
setTimeout(function () {
if (el.value.indexOf("333") != 0) {
el.value = value;
}
}, 0);
});
<input type="text" value="333" id="nine" />
I'd suggest using 2 inputs that look like a single input, with the first one readonly. See this fiddle: https://jsfiddle.net/39whrqup/2/
<input readonly value="333" class="static-input">
<input class="nonstatic-input">
.static-input {
margin-right: -20px;
width: 50px;
border: 0;
}
.nonstatic-input {
border: 0;
}
When reading the user input you will have to prepend the static portion, naturally:
var userInput = document.querySelector('input.static-input').value +
document.querySelector('input.nonstatic-input').value;