简体   繁体   中英

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. 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 ''. 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:

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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