jquery - Assign values to Button Randomly -
i have 1 random variable selects random numbers between 1-10. want create question in user have guess random number generated. want give user 4 options.
i have 4 distinct variables a
,b
,c
, rand
.
function generateoption() { var rand = math.floor((math.random() * 9)+1); var arr = []; var n,a,b,c; for(var i=0; i<3; i++) { do{ n = math.floor(math.random()*9+1); } while(arr.indexof(n) !== -1&&n!=rand); arr[i] = n; // alert(arr[i]); } a=arr[0]; b=arr[1]; c=arr[2]; alert(a+" "+b+" "+c+" "+rand); }
i have 4 buttons
<table style=" margin: 0 auto;"> <tr> <td><input id="nextbutton3" type="button" class="finish"></td><td></td><td><input id="nextbutton4" type="button" class="finish"></td> </tr> <tr> <td><input id="nextbutton5" type="button" class="finish"></td><td></td><td><input id="nextbutton6" type="button" class="finish"></td> </tr> </table>
i can assign values buttons
$(function() { $("#nextbutton3").val(a); $("#nextbutton4").val(b); $("#nextbutton5").val(c); $("#nextbutton6").val(rand); });
but set correct answer stick button6 always.
how can assign value a
,b
,c
, rand
buttons randomly? please help
you assignment needs random. i'm going suggest different workflow:
function generateoptions() { var randomvalues = []; var currentvalue; // first, generate 4 random values in 1-10 range while(randomvalues.length < 4) { currentvalue = math.floor(math.random() * 9) + 1; // avoid duplicates if(randomvalues.indexof(currentvalue) < 0) { randomvalues.push(currentvalue); } } // here, randomvalues has 4 values // pick 1 "right" one: var correctvalue = randomvalues[math.floor(math.random() * 4)]; return { options: randomvalues, correct: correctvalue, }; }
then, prepare page:
$(function() { var setup = generateoptions(); // assign each of values button $("#nextbutton3").val(setup.options[0]); $("#nextbutton4").val(setup.options[1]); $("#nextbutton5").val(setup.options[2]); $("#nextbutton6").val(setup.options[3]); // that's selector i've deduced markup. feel free change $("input.finish").on("click", function() { // need parse .val() int, since returns string var selectedvalue = parseint($(this).val(), 10); if(selectedvalue === setup.correct) { alert("correct!"); } else { alert("wrong!"); } }); });
a simple working example: http://jsbin.com/moyuqaha/1/edit?html,js,output (press ctrl+enter while focused on js window reload numbers)
Comments
Post a Comment