简体   繁体   English

jQuery-根据单选单击更改标签文本

[英]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. 我想知道jQuery是否可以根据单击的单选按钮来更改页面上的文本。

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>
$(':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 . jsFiddle

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. 这样会将标签更改为您在该value属性中放置的任何内容。 For better results, I'd use class names on the radio buttons and ids on the labels you wish to change. 为了获得更好的结果,我将在单选按钮上使用类名称,并在要更改的标签上使用ID。

Edit: Here's a working example . 编辑:这是一个有效的示例

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');
};
<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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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