In this blog I will explain how to add item in listbox by using Java script and how to get selected item from the HTML listbox.
First create a simple listbox and a button:
<table>
<tr>
<td valign="top">Select Product: </td>
<td>
<select size="5" id="listProduct">
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Enter"/>
</td>
</tr>
</table>
Create a JavaScript function that add items in java script and call that function on the form load:
function addProduct() {
var arrProduct = ["KeyBoard", "Monitor", "USB Drive", "Speaker", "Mouse"];
for (var i = 0; i < arrProduct.length; i++) {
var opt = document.createElement("option");
document.getElementById("listProduct").options.add(opt);
opt.text = arrProduct[i];
opt.value = arrProduct[i];
}
}
<body onload="addProduct()">
Then create a JavaScript function that get a selected item from a listbox and display it in alert box, also call that function on the click of button:
function getSelectedProduct() {
var list = document.getElementById('listProduct');
for (var i = 0; i < list.options.length; ++i) {
if(list.options[i].selected)
alert(list.options[i].value);
}
}
<input type="button" value="Enter" onclick="getSelectedProduct()" />
Thank you for reading this blog and I think this will help you a lot.
Anonymous User
13-May-2019Nice Article.