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
3 Answers
Reset to default 4I 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/