简体   繁体   English

5个单选按钮随机填充吗?

[英]5 radio buttons fill up randomly?

Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly. 嗨,我正在尝试制作五个按钮,如您所见,当您按“单击我”时,我想要一个功能,它将随机填充五个按钮。

It's like a random generator for stats for a game. 就像游戏统计信息的随机生成器一样。

I don't know if I'm doing it all wrong but I think I need some other coding for this. 我不知道我做错了什么,但我想我需要一些其他编码。

Can anyone that can help me? 谁能帮助我?

This is what I have: 这就是我所拥有的:

<button onclick='myFunction()'>click me</button>

<div id="demo">
<Input type = radio Name = r1> 
<Input type = radio Name = r2> 
<Input type = radio Name = r3> 
<Input type = radio Name = r4>
<Input type = radio Name = r5> 
</div>


<script type="text/javascript">

    function myFunction() {
    document.getElementById('demo').innerHTML = '';
    var num = 3;
    var noOfButtons = Math.floor(Math.random() * num);
    console.log(noOfButtons);
    for (var i = 0; i < noOfButtons; i++) {

    var box = document.createElement();
        document.getElementById('demo');
        }
    }
</script>

not exactly sure what your looking for. 不确定您要寻找什么。 I threw this JSFiddle together. 我把这个JSFiddle放在一起了。 Take a look and see if its what you're looking for. 看一看,看看它是否在寻找。

<button id='button1'>click me</button>
<div id="demo">
    <input type='radio' id='r1'>
    <input type='radio' id='r2'>
    <input type='radio' id='r3'>
    <input type='radio' id='r4'>
    <input type='radio' id='r5'>
</div>

.

     var button1 = document.getElementById('button1');
     button1.onclick = function () {
         var noOfButtons = 5;
         var pick = Math.floor(Math.random() * noOfButtons) + 1;
         var radioBtn = document.getElementById('r' + pick);
         radioBtn.checked = true;
     }

[edit] [编辑]

I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo 's html to ''. 我认为您要尝试随机检查有限数量的电台,在这种情况下,无需将demo的html设置为。 I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function: 我将myRadiosmyRadios到无线电的标签中(以防页面上有其他无线电不希望包含在随机检查中),然后使用以下功能:

function myFunction() {
    var radios = document.getElementsByClassName('myRadios');
    for (var i=0; i<radios.length; i++)
    {
        radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
    }
}

Here is aa working fiddle . 这是一个工作的小提琴 Let me know if this is the functionality you were looking for or if you have any questions about how it works :) 让我知道这是您正在寻找的功能还是对它的工作方式有任何疑问:)

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

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