Users Pricing

blog

home / developersection / blogs / binding data in listbox and get selected value from listbox using java script

Binding Data in Listbox And Get Selected Value From Listbox Using Java Script

Chris Anderson 20605 07 Sep 2011 Updated 18 Sep 2014

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.


hi I am software developer at mindstick software pvt. ltd.


1 Comments