繁体   English   中英

使用JavaScript获取SelectedValue ASP.NET RadiobuttonList

[英]Use JavaScript to Get 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);
            }
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM