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:
            <td valign="top">Select Product: </td>
                <select size="5" id="listProduct">
            <td colspan="2">
                <input type="button" value="Enter"/>


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");
                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) {

 <input type="button" value="Enter" onclick="getSelectedProduct()" />

Thank you for reading this blog and I think this will help you a lot.

  Modified On Sep-18-2014 01:23:59 PM

Leave Comment