简体   繁体   中英

How to add jquery onclick event to asp radiobutton?

I have asp.net code:

<asp:RadioButton ID="RadioButton1" CssClass="rb1" GroupName="grp1" runat="server" />
<br/>
<asp:RadioButton ID="RadioButton2" CssClass="rb2" GroupName="grp1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

In the browser it look like this:

<span class="rb1">
<input id="MainContent_RadioButton1" type="radio" value="RadioButton1" name="ctl00$MainContent$grp1">
</span>
<br>
<span class="rb2">
<input id="MainContent_RadioButton2" type="radio" value="RadioButton2" name="ctl00$MainContent$grp1">
</span>
<input id="MainContent_TextBox1" type="text" name="ctl00$MainContent$TextBox1">

How to add "onclick" event to RadioButton1, so it will clear TextBox1 when clicked?

I'm trying to do this:

<script type="text/javascript" language="javascript">
    $("input rb1").click(function () {
        alert('1');
    });
</script>

It does nothing.

You could set the ClientIDMode attribute to static on the asp checkbox and textbox control and use jquery to register the click event and empty the textbox's value.

<asp:RadioButton ID="RadioButton1" CssClass="rb1" GroupName="grp1" runat="server" ClientIDMode="Static"/>

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"/>

<script type="text/javascript">
$(function(){
   $("input#RadioButton1").click(function(){
      $("input#TextBox1").text("");
   });
});
</script>

you are missing a . the class selector requires a dot like .rb1

 <script type="text/javascript"> $("input .rb1").click(function () { alert('1'); }); </script> 

after the @SKS pointed out curiously :p , $("input .rb1") means to look for element(s) with class=rb1 inside(read children of) the input element that doesn't make sense you need to use the selector $("input.rb1") like

<script type="text/javascript">
    $("input.rb1").click(function () {
        alert('1');
    });
</script>

that will select the element(s) with class=rb1

$('#mainContent_RadioButton1').click(function() {

要么

$('.rb1 input').click(function() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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