- HTML only (semi) solution
Assuming you want to use numbers like you do in your example, you can also use an input field with a number type.
I've included some CSS to always show the arrows in Chrome. In other browsers, the arrows are always shown.
Beware that this only works for numbers, not strings or other types.
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity: 1;
}
<input value="1" min="1" max="9" type="number" style="width:30px"/>
- Javascript solution
This solution involves a bit of simple Javascript, but works with strings too. You can style the <div>
tags however you'd like so they resemble up and down buttons, that's up to you.
var options = [ "Orange", "Kiwi", "Banana", "Strawberry", "Pear" ]
// The current index of the options array
var current = 0;
// This function removes 1 from the currently selected option index and sets the field value
function prev(){
if(current > 0) current--;
setFieldValue(options[current]);
}
// This function adds 1 to the currently selected option index and sets the field value
function next(){
if(current < options.length-1) current++;
setFieldValue(options[current]);
}
function setFieldValue(text){
document.getElementById("field").value = options[current];
}
// Call the method so the field doesn't start out empty
setFieldValue(options[current]);
div.button {
display: block;
position: absolute;
width: 20px;
height: 10px;
text-align: center;
background-color: gray;
color: white;
line-height: 10px;
cursor: pointer;
}
div.button:hover {
background-color: lightgray;
}
div.one {
right: 0;
top: 0;
}
div.two {
right: 0;
bottom:0;
}
div.field-wrapper {
display: inline-block;
position: relative;
}
input#field {
background-color: white;
}
<div class="field-wrapper">
<input id="field" disabled/>
<div class="button one" onclick="prev();">^</div>
<div class="button two" onclick="next();">v</div>
</div>