[英]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.