从javascript获取ASPX radiobutton文本或值

时间:2013-02-21 08:04:43

标签: javascript asp.net radio-button

ASPX radiobuttons位于数据主义模板

<asp:RadioButton ID="RadioButton1" runat="server"  
        GroupName="rdb" 
        Text='<%#  Eval("type1") %>'  
        onclick="Getr1(this)"/>

JavaScript

function getr1(val){
    alert(val)
}

如果我在任何html控件中使用此函数,它将返回一个值,但它不能在aspx radiobuttons中工作。我使用这段代码:onchange="GetQty(this.options[this.selectedIndex].value)"从aspx下拉列表中获取所选索引,它运行得很好,也许有人可以帮我找出aspx rb的正确语法。我已经尝试了onclick="Getr1(this.options[this.checked].value)",感谢提前

2 个答案:

答案 0 :(得分:1)

您的代码很好,只需要稍作修改。

<asp:RadioButton ID="RadioButton1" runat="server"  
    CliientIDMode="Static" GroupName="rdb" 
    Text='<%#  Eval("type1") %>' />

 <asp:Label ID="Label1" runat="server" style="font-size: x-small"
    Text='<%# Eval("type1") %>'></asp:Label>

jQuery获取 RadioButton文字

$("#RadioButton1").click(function{
    alert( $(this).siblings('label').text());
});

jQuery用于获取RadioButton旁边的 asp:标签文字

$("#RadioButton1").click(function{
    alert( $(this).siblings('span').text());
});

希望有所帮助:)

答案 1 :(得分:0)

试试这个JavaScript。

function Getr1(elm) {
    var nextElm = elm.nextSibling;
    //catching white space, comments etc...
    while (nextElm && nextElm.nodeType != 1) {
        nextElm = nextElm.nextSibling
    }
    alert(nextElm.innerHTML);
}

原因:asp:RadioButton在浏览器中以这样的方式呈现

<input id="MainContent_RadioButton1" type="radio" onclick="Getr1(this);" 
     value="RadioButton1" name="ctl00$MainContent$rdb">
<label for="MainContent_RadioButton1">your rendered text here</label>

如果你使用jQuery,它就会像这样简单。

function Getr1(elm) {
    alert( $(elm).next().html() );
}