Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find selected item from radiobutton list using javascript

I need to find selected item from radiobutton list using javascript... Here is my code

  <asp:RadioButtonList name="test" ID="RadioButtonList1"  runat="server">
    <asp:ListItem Text="List1" Value="1"></asp:ListItem>
    <asp:ListItem Text="List2" Value="3"></asp:ListItem>
    </asp:RadioButtonList>
    <asp:Button Text="test" runat="server" OnClientClick=" GetListItem()" />

script:

<script type="text/javascript" language="javascript">
function GetListItem() {
    var id = document.getElementById("<%=RadioButtonList1.ClientID%>");
    alert(id.selectedItem.value())//Error: 'selectedItem' is null or not an object;
}

How can i find selectedItem from that list

like image 262
Suresh Avatar asked Dec 09 '22 02:12

Suresh


1 Answers

Here's a fairly straightforward way of accomplishing this. If you want to find the selected list item when the user clicks, add an onclick attribute to each of the items in the RadioButtonList with the javascript function to call when the list item is clicked. The "this" parameter will pass the list item to the javascript function:

<asp:RadioButtonList name="test" ID="RadioButtonList1"  runat="server">
<asp:ListItem Text="List1" Value="1" onclick="myListItemClick(this);"></asp:ListItem>
<asp:ListItem Text="List2" Value="3" onclick="myListItemClick(this);"></asp:ListItem>
</asp:RadioButtonList>

Note that the 'onclick' attribute is not recognized by ASP.NET intellisense for ListItem controls, but it will still fire the client-side javascript function.

Now in your javascript function:

function myListItemClick(e) {
    alert('Selected value: ' + e.value);
}

Make sure to add the "Value" attribute to all of your list items for this to work properly (as you have already done).

If you don't want to do this when the user clicks, you can accomplish it this way. In your markup:

<script type="text/javascript" language="javascript">
        var radioList = '<%= RadioButtonList1.ClientID %>';
</script>

Then in your javascript:

function getSelectedListItem() {
   var radioButtonList = document.getElementById(radioList);
   var listItems = radioButtonlist.getElementsByTagName("input");
   for (var i = 0; i < listItems.length; i++) {
       if (listItems[i].checked) {
          alert("Selected value: " + listItems[i].value);
       }
   }
}
like image 63
lunarquaker Avatar answered Apr 27 '23 17:04

lunarquaker