How can I select my newly added value in the select box (dropdown) after the value that was inputted into the textbox and the add button was clicked?
<html>
<head>
<script>
function addref(value) {
var x = document.getElementById("thebox");
var option = document.createElement("option");
option.text = value
x.add(option,x.options[null])
}
</script>
</head>
<body>
<form>
<select id="thebox">
</select>
</form>
<br>
<input type="text" id="theinput"/>
<input type="button" value="Add" name="B1" onclick="addref(document.getElementById('theinput').value)"/>
</body>
</html>
Try this:
x.selectedIndex = x.options.length - 1;After this you can retrieve the value using
or
<select>at MDN.Also, instead of
x.add(option,x.options[null])rather use simplyx.add(option). This will add the newly createdoptionat the end of theoptions. The second argument is supposed to be an integer, which represents an index position where to add a new option.