Steak
Steak

Reputation: 544

HTML Number Input: Only Allow Arrow Buttons

Here is what I mean:

Input Image

Is it possible to only allow input via clicking the arrow buttons, and NOT from actually typing?

Ie: I could not type in "11", but if I click the up arrow 11 times then it will go to 11?

Here is my input field right now:

        <input type="number" min="00" max ="99" id="timer02_min" 
        maxlength="2" value="00">

Is there some native way of doing this? Or should I look more into buttons and some styling?

Upvotes: 1

Views: 3409

Answers (2)

allancoding
allancoding

Reputation: 549

function change(n) {
  var num = document.getElementById("num");
  var number1 = num.innerHTML;
  var number = Number(number1);
  if (n != "s") {
    number = number + n;
  }
  if (number < 0) {
    number = 0;
  }
  if (number > 99) {
    number = 99;
  }
  var num2 = number.toString();
  if (num2.length == 1) {
    var num1 = number;
    number = "0" + num1;
  }
  document.getElementById("num").innerHTML = number;
}
change("s");
.input {
  border-style: solid;
  border-color: gray;
  border-width: 1px;
  border-radius: 2px;
  padding: 1px;
  height: 26px;
  width: 40px;
  text-align: left;
  position: relative;
  padding-left: 10px;
}
.spinner-button {
  position: absolute;
  top: 0px;
  right: 0px;
}
#inc-button {
  padding-top: 3.5px;
  background-color: #ccc;
  width: 14.5px;
  text-align: center;
  margin-bottom: 1px;
  height: 10px;
  line-height: 10px;
  cursor: pointer;
  border: none;
  user-select: none; /* Standard */
}
#dec-button {
  cursor: pointer;
  padding-top: 3px;
  background-color: #ccc;
  width: 14.5px;
  text-align: center;
  margin: 0px;
  height: 10px;
  line-height: 10px;
  border: none;
  user-select: none; /* Standard */
}
#inc-button:hover, #dec-button:hover {
  background-color: #b5b5b5;
}
<div id="timer02_min" class="input">
  <div id="num">00</div>
  <div class="spinner-button">
    <div onclick="change(1);" id="inc-button">+</div>
    <div onclick="change(-1);" id="dec-button">-</div>
  </div>
</div>

The Number you want to start put it in the #num div.

Upvotes: 3

vanowm
vanowm

Reputation: 10221

Use event.preventDefault() in keydown event;

// no keyboard
document.getElementById("timer02_min").addEventListener("keydown", e => e.preventDefault());

// allow up/down keyboard cursor buttons
document.getElementById("timer02_min2").addEventListener("keydown", e => e.keyCode != 38 && e.keyCode != 40 && e.preventDefault());
no keyboard:
<input type="number" min="00" max ="99" id="timer02_min" 
        maxlength="2" value="00">
<br>
with up/down cursor keys:
<input type="number" min="00" max ="99" id="timer02_min2" 
        maxlength="2" value="00">

Upvotes: 5

Related Questions