我在.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>
默认选择第二个无线电。有没有办法让我确定用户是否还没有选择第一个选项,即&#34;拒绝&#34;他们在执行某项行动时仍然被选中?
E.g:
function checkRbList() {
var rbl = document.getElementById(<%= rbList.ClientID %>);
//if "decline" is still selected, alert('You chose to decline')...
}
答案 0 :(得分:2)
假设您已呈现此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.");
}
};
})();
&#13;
<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>
&#13;
答案 1 :(得分:0)
我发现了一种有效的方法:
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);
}
}
}
});