最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use a button to select a random radio? - Stack Overflow

programmeradmin2浏览0评论

I'm guessing the use of js is going to be needed, but i have a button and 4 radio's. When a user presses the 'random' button, a random radio button is to be selected. Any suggestions wele :)

I'm guessing the use of js is going to be needed, but i have a button and 4 radio's. When a user presses the 'random' button, a random radio button is to be selected. Any suggestions wele :)

Share Improve this question asked Sep 4, 2011 at 9:06 Draknyte1Draknyte1 243 silver badges9 bronze badges 3
  • Yes, you'd need JavaScript... what do you know about it? – Felix Kling Commented Sep 4, 2011 at 9:08
  • Not alot at all, still trying to learn it :) – Draknyte1 Commented Sep 4, 2011 at 9:12
  • Then I remend reading the MDN JavaScript Guide, an introduction to DOM, and quirksmode's articles about event handling. – Felix Kling Commented Sep 4, 2011 at 9:17
Add a ment  | 

3 Answers 3

Reset to default 4

I assume your radio is in a group, therefore will have an index in that group.

You can therefore simply use

var randomnumber=Math.floor(Math.random()*4)

to generate the index, and there you have your radio button to select

In this HTML I made four radio buttons in the same group (radioGroup)

In Javascript I get all the buttons in the group and "check" one randomly.

function callRandom() {
  var array = document.getElementsByName('radioGroup');
  var randomNumber=Math.floor(Math.random()*4);

  array[randomNumber].checked = true;
}
callRandom();
<input type="button" value="Random" onclick="callRandom();"><br>
<input type="radio" name="radioGroup" value="1"> One<br>
<input type="radio" name="radioGroup" value="2"> Two<br>
<input type="radio" name="radioGroup" value="3"> Three<br>
<input type="radio" name="radioGroup" value="4"> Four

Hope this helps.

here is a jQuery version :

$('form :radio:eq('+Math.round(Math.random()*($('form input:radio').length-1))+')').attr('checked','checked');

I made a jsFiddle -> http://jsfiddle/mica/TFNmB/

发布评论

评论列表(0)

  1. 暂无评论