-1

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.

Jack Johnson
  • 1,327
  • 3
  • 12
  • 18

3 Answers3

1

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.

Danny Hurlburt
  • 674
  • 1
  • 8
  • 15
1

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" />
0

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;
William B
  • 1,411
  • 8
  • 10