BigJobbies
BigJobbies

Reputation: 4343

jQuery - Changing label text based on radio click

I was wondering if it is possible with jQuery to change text on a page based on what radio button is clicked.

I have the following code, and i want to change the label text to "first radio was clicked" or "second radio was clicked" based on which of the radio buttons were clicked.

<input type="radio" name="first" value="yes" id="firstradio">
<input type="radio" name="first" value="no" id="secondradio"> 

<label class="changeme">Initial text goes here and is happy</label>

Upvotes: 0

Views: 12014

Answers (4)

Sravan Kumar
Sravan Kumar

Reputation: 1457

<asp:RadioButtonList ID="rbtnType" runat="server" RepeatDirection="Vertical">
<asp:ListItem Value="C">Contract </asp:ListItem> <asp:ListItem Value="I">Independent</asp:ListItem> 
<asp:ListItem Value="O">OutSource </asp:ListItem> </asp:RadioButtonList>  <br />
 <asp:Label ID="lblLaborType" runat="server" ></asp:Label>  
<script type="text/javascript">
   $(document).ready(function ()     
     {   
      $("#<%=rbtnType.ClientID%>").change(function () 
    {    
      var rbvalue = $("input[@name=<%=rbtnType.ClientID%>]:radio:checked").val();   
        if (rbvalue == "C")
      {        
            $('#<%=lblLaborType.ClientID %>').html('Do this');  
   } 
      else if (rbvalue == "I")
   {         
      $('#<%=lblLaborType.ClientID %>').html('else this'); 
    }

    else if (rbvalue == "O") 
     {
           $('#<%=lblLaborType.ClientID %>').html('or else this');        
    }
    }); 
    }); 
   </script> 

Upvotes: 0

user319198
user319198

Reputation:

It will be something like below :

$('input[name=first]').change(function()  {
    // change the page per this logic
    switch ($('input[name=first]:checked').val()) {
        case 'yes':
            $('#Message').text('first radio was clicked'); break;
        case 'no':
            $('#Message').text('second radio was clicked'); break;
        default:
            $('#Message').text('select choice');
};

Upvotes: 1

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

For your code:

$('input[type=radio]').change(function(evt) {
    $('.changeme').html($(this).val());
});

That'll change the label to whatever you put in that value attribute. For better results, I'd use class names on the radio buttons and ids on the labels you wish to change.

Edit: Here's a working example.

Upvotes: 1

alex
alex

Reputation: 490233

$(':radio').click(function() {

   var index = $(this).index(),
       // Modify this to suit all ordinals
       ordinal = (index == 0) ? 'first' : 'second';    

   $('.changeme').text(ordinal + ' radio was clicked');

});

jsFiddle.

Upvotes: 1

Related Questions