繁体   English   中英

更改单选按钮上的div文本单击

[英]change div text on radion button click

我想将单选按钮值放在状态div中。 状态div的文本应根据用户选择的单选按钮进行更改。 我在下面使用的代码无法正常工作。 请帮忙。 谢谢!

HTML代码:

 <form action="">
     <input type="radio" name="sex" value="male">Male<br>
     <input type="radio" name="sex" value="female">Female<br>
     <div id="status"></div>
  </form>​

JS代码:

 $(document).ready(function () {
    RadioStatus="";

    $("input[type='radio']:checked").each( function()
    { 
        if ($(this).attr('checked');)
              RadioStatus=$(this).val();
              $("#status").text(RadioStatus);
        });

    $("input[type='radio']").change(function()  
     {
             RadioStatus= $('input[type='radio']:checked').val()
            $('#status').text(RadioStatus);        
    });
});

这应该工作:

$("input[type='radio']").click(function() {
    $('#status').text($(this).val());
});

对您的代码进行一些细微调整,使其可以正常工作:

$(document).ready(function () {
    RadioStatus="";

    $("input[type='radio']:checked").each( function()
    { 
        if ($(this).attr('checked'))
              RadioStatus=$(this).val();
              $("#status").text(RadioStatus);
        });

    $("input[type='radio']").change(function()  
     {
             RadioStatus= $('input[type="radio"]:checked').val();
            $('#status').text(RadioStatus);        
    });
});​

请参阅: http//jsfiddle.net/f6Tru/

..或者你真的可以通过使用techfoobar的简化一下:

$(document).ready(function () {
    $("input[type='radio']").click(function() {
        $('#status').text($(this).val());
    });
});​

代替。 参见: http : //jsfiddle.net/RrhYM/

您在单引号中有问题'

更改:

RadioStatus= $('input[type='radio']:checked').val()

至:

RadioStatus= $('input[type="radio"]:checked').val()

试试这个代码

$('input[name ^=sex]').click(function() {
        $('#status').text($(this).val());
});

只需使用change来确定已选中单选按钮。 然后使用htmltext将所选单选按钮的值附加到<div id="status">

$(document).ready(function () {
    $('input[type=radio]').on("change", function() {
        $('#status').html($(this).val());
        // Alternative
        // $('#status').text($(this).val());
    });
});​

演示

演示

$("input:radio").click(function() { //use $("input:radio[name='sex']").click if more radio buttons there
  $('#status').text($(this).val());
});​

您可以使用以下JS代码实现这一目标:

$("input").click(function(e){
     var selectedValue = e.currentTarget.value;                 
    $('#status').html(selectedValue );       
});

暂无
暂无

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

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