jQuery动态单选按钮 [英] Jquery-Dynamic Radio Buttons

查看:81
本文介绍了jQuery动态单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在容器中创建单选按钮.从另一个容器中的Combobox中选择的值来提供单选按钮的总数,当我尝试执行此操作时,即使提供的数字大于1,我也只显示了一个单选按钮,我也得到了这些单选按钮附加到先前的选择按钮上,而不是我需要在更改选择时清除内容,而仅应显示新的按钮数量.

I am trying to create radio buttons in a container. The total number of radio buttosn is supplied from the value selected in Combobox that is in another container, when I am trying to do this, I am getting only 1 radio button displayed even the supplied number is more than 1, also I am getting those appended to the previous selection buttons, instead of that I need to clear the contents when the selection is changed and new number of buttons should only be displayed.

$(document).ready(function(){

$("#choice").change(function(){

    var radio_name=$("#choice option:selected").text();
    var a=$("#choice option:selected").val();
    var element=$('<input type="radio" name='+ radio_name +'/><br>');
    for(i=1;i <= a;i++){

       element.prependTo('#reports');
    }
 });

 });
      </script> 
     </head>
     <body>
    <div style="padding-top:20px;padding-left: 300px;color: orange;">
    Select Your Choice:&nbsp;&nbsp;<select id='choice' style="width:100px;">
       <option>Select Your Choice</option>
    <option value="4">Sales</option>
    <option value="2">Income</option>
    <option value="3">Consumer</option>
    <option value="5">Exports</option>
    </select>

    </div>
    <div id="reports" style='float: left;padding-top: 100px;color:orange;'>

    </div>

推荐答案

element的值不能在HTML中重复.

element's value can't be duplicated in the HTML.

您需要在循环内定义element,或者,因为我看不到将无线电定义为变量的任何用处,所以您可以简单地做到这一点:

You need to define element inside the loop, or, since I don't see any use of defining the radios into a variable you can simply do:

$("#choice").change(function(){

    $( '#reports' ).empty();

    var radio_name=$("#choice option:selected").text();
    var a=$("#choice option:selected").val();

    for(i=1;i <= a;i++)
        $( '<input type="radio" name='+ radio_name +'/><br>' ).prependTo('#reports');

});

empty()用于清除容器.

这篇关于jQuery动态单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆