How to get Selected ListBox Item using JavaScript

This is a quick post in response to a question asked by my one of the follower on Facebook and the answer is pretty simple.

Here is the question I have been asked:-

Hi,
I want to send value of selected item in listbox to another page by using jquery, can you reply me the code.
Hardi Mhamad, Iraq

And my coded response is:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function MethodCall() {
            var list = document.getElementById('ListBox1');
            var indx = list.selectedIndex;
           
            rep.innerHTML = list[indx].value;
           
            document.location.href = 'http://www.itorian.com?Val=' + list[indx].value;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server">
            <asp:ListItem>Microsoft</asp:ListItem>
            <asp:ListItem>Oracle</asp:ListItem>
            <asp:ListItem>Adobe</asp:ListItem>
            <asp:ListItem>Apple</asp:ListItem>
        </asp:ListBox>
        <br />
        <div id="rep"></div>
        <br /><br />
        <input id="Button1" type="button" value="Click Me" onclick="MethodCall()"/>
    </div>
    </form>
</body>
</html>

So, I grabbed the value from ListBox using ‘list[ListBox1.selectedIndex].value’ and then added the same with URL Parameter to receive it on next page, all fires up when user clicks the button.

Comments

  1. thank you it is a good answer but I want to send the index variable by $.ajax in jquery
    I want to send it without clicking button just by selecting the index, then send the variable to another page..

    ReplyDelete
    Replies
    1. Means you want to navigate on another page when user selects the item from ListBox and at the same time you also want to know what index/value user clicked on using jquery/javascript. Right? The best solution is here. http://www.asynccontrols.com/Ajax-List-Box/

      Delete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples