JSFiddle - React, Tailwind, and code Playground
HTML
<select multiple id="select">
<option> 1</option>
<option> 2</option>
<option> 3</option>
</select><br><br>
<input type="text" id="NewValue">
<button id="myBtn" onclick="addValue()">
Add Value
</button> <br><br>
<button onclick="log()">
Log selectedOptions
</button><br><br>
CSS
select{
width:50px;
/*size : 10;*/
height: 200px;
}
JavaScript
function log(){
//console.log(document.getElementById("select"));
console.log(document.getElementById("select").selectedOptions);
}
function addValue(){
//code pour le opt ici https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/add
if(document.getElementById("NewValue").value != ""){
let opt = document.createElement("option");
opt.value = opt.text = document.getElementById("NewValue").value;
opt.selected = "selected";
document.getElementById("NewValue").value = "";
document.getElementById("select").add(opt);
}
}
//Code pour le enter pris ici : https://www.w3schools.com/howto/howto_js_trigger_button_enter.asp
// Get the input field
var input = document.getElementById("NewValue");
// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
// If the user presses the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});