0

If I have a drop down menu like the following:

<select>
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
</select>

How could I create two buttons that when pressed would change the chosen option? So if Cat was selected and the up arrow was pressed, Dog would become selected. The same would happen for a down arrow. When Dog was selected and the down arrow is clicked Cat would become selected.

Raviga
  • 117
  • 1
  • 16
  • If the up arrow is pressed when the selection is dog, should it go to the other end of the collection, or do nothing? – Ryan Wilson Jul 17 '18 at 13:39
  • 1
    Possible duplicate of [Changing the selected option of an HTML Select element](https://stackoverflow.com/questions/7373058/changing-the-selected-option-of-an-html-select-element) – JSON Derulo Jul 17 '18 at 13:40
  • 1
    Please show us what you have tried. Stackoverflow is not a free code writing service or a *"how to"* tutorial service. The objective here is for you to research the basics and when you have code that doesn't work as expected others help fix **your code** – charlietfl Jul 17 '18 at 13:43

2 Answers2

1

You can do it like this:

var ddl = document.getElementById("s")

function change(x) {
  if (x.value === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else {
    ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
  <option>Dog</option>
  <option>Cat</option>
  <option>Bird</option>
</select>
<input id="d" type="button" value="down" onclick="change(this); return false;">
<input id="u" type="button" value="up" onclick="change(this); return false;">
Scath
  • 3,777
  • 10
  • 29
  • 40
0
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>
<script>
$(document).ready(function(){
$("#up").click(function(){
var selecteddata = $("#data option:selected").val();
  var next = parseInt(selecteddata)-1;
  $("#data").val(next.toString());
});

$("#down").click(function(){
var selecteddata = $("#data option:selected").val();
  var next = parseInt(selecteddata)+1;
  $("#data").val(next.toString());
 });
});
</script>
</head>
<body>

<select id="data">
<option value="0">Dog</option>
<option value="1">Cat</option>
<option value="2">Bird</option>
</select>
<input type="button" value="UP" id="up" />
<input type="button" value="Down" id="down" />
</body>
</html>
Rohit Chauhan
  • 1,119
  • 1
  • 12
  • 30