使用JavaScript获取SelectedValue ASP.NET radiobuttonList



我在.aspx页面上有以下单选按钮列表:

<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>

默认情况下选择第二个收音机。我有没有办法确定用户是否没有选择第一个选项,即在执行操作时仍选择"衰落"?

例如:

function checkRbList() {
  var rbl = document.getElementById(<%= rbList.ClientID %>);
  //if "decline" is still selected, alert('You chose to decline')...
}

以下工作应该完成工作:

var rbl = document.getElementById("<%= rbList.ClientID %>");    
var value = rbl.value;
if(value === 'decline')
    alert()

假设您呈现此HTML:

<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>

您可以使用 document.getElementsByName() 。然后使用:

document.getElementsByName("rbList")您将获得 NodeList

这是功能:

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.
    }
  }
}

检查"decline"是否仍然选择:

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

类似的东西:

(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>

我找到了一种正在工作的方法:

var targetValue = "decline";
$('#<% = myBtn.ClientID %>').click(function () {
    var items = $("#<% = rbList.ClientID %> input:radio");
    for (var i = 0; i < items.length; i++) {
        if (items[i].value == targetValue) {
            if (items[i].checked) {
                alert(items[i].value);
            }
        }
    }
});

最新更新