Search code examples
javascriptc#asp.netradiobuttonlist

Use JavaScript to Get SelectedValue ASP.NET RadiobuttonList


I have the following radio button list on an .aspx page:

<asp:RadioButtonList ID="rbList" runat="server">
  <asp:ListItem Text="I accept" Value="accept" />
  <asp:ListItem Text="I decline" Value="decline" Selected="True" />
</asp:asp:RadioButtonList>

The second radio is selected by default. Is there a way for me to determine if a user hasn't selected the first option, i.e., "decline" is still selected when they perform an action?

E.g.:

function checkRbList() {
  var rbl = document.getElementById(<%= rbList.ClientID %>);

  //if "decline" is still selected, alert('You chose to decline')...

}

Solution

  • Assuming you have this HTML rendered:

    <label>
      I accept
      <input id="rbList_0" name="rbList" type="radio" value="accept" />
    </label>
    <label>
      I decline
      <input id="rbList_1" name="rbList" checked="true" type="radio" value="decline" />
    </label>
    

    You can use document.getElementsByName(). Then by using:

    document.getElementsByName("rbList") you'll get a NodeList.

    This is the function:

    function checkRbList() {
      var rbl = document.getElementsByName("rbList"), len = rbl.length;
    
      for (var i = 0; i < len; i++) {
        if (rbl[i].checked) { // If checked?
          return rbl[i].value; // Returns the selected value.
        }
      }
    }
    

    To check if "decline" is still selected:

    var targetValue = "decline";
    if (checkRbList() === targetValue) {
      alert("You chose to decline.");
    }
    

    Something like this:

    (function() {
    
      var targetValue = "decline";
    
      function checkRbList() {
        var rbl = document.getElementsByName("rbList"),
          len = rbl.length;
    
        for (var i = 0; i < len; i++) {
          if (rbl[i].checked) { // If checked?
            return rbl[i].value; // Returns the selected value.
          }
        }
      }
    
      var btnValidate = document.getElementById("btnValidate");
      btnValidate.onclick = function() {
        console.log(checkRbList()); // Prints the selected value.
        if (checkRbList() === targetValue) {
          alert("You chose to decline.");
        }
      };
    
    })();
    <label>
      I accept
      <input id="rbList_0" name="rbList" type="radio" value="accept" />
    </label>
    <label>
      I decline
      <input id="rbList_1" name="rbList" checked="true" type="radio" value="decline" />
    </label>
    
    <button id="btnValidate" type="button">Validate</button>