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.

Upvotes: 1

Views: 12761

Answers (3)

Rafay
Rafay

Reputation: 31043

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

Upvotes: 2

Rob Angelier
Rob Angelier

Reputation: 2333

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>

Upvotes: 3

orolo
orolo

Reputation: 3951

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

or

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

Upvotes: 0

Related Questions