javascript - How to check if the user input is the correct answer or not? -


i making online application children picks random image database using following code:

<script type="text/javascript"> var random_images_array = ['apple.gif', 'book.gif',...]  function getrandomimage(imgar, path)  { path = path || 'images/'; var num = math.floor( math.random() * imgar.length ); var img = imgar[ num ]; var imgstr = '<img src="' + path + img + '" alt = "">'; document.write(imgstr); document.close(); } </script> 

my question how can tell computer whether input user correct answer or not? example if programme showing apple image, user should type “apple” , system should return “correct” message. p.s. name of images represent content of image.

the simplest way check user input against name of image, first, make num global variable can access in function. then, write function check user input against item in random_images_array @ index num - extension. here final code:

<script type="text/javascript"> var random_images_array = ['apple.gif', 'book.gif',...] var num = 0;  function getrandomimage(imgar, path)  {     path = path || 'images/';     num = math.floor( math.random() * imgar.length );     var img = imgar[num];     var imgstr = '<img src="' + path + img + '" alt = "">';     document.write(imgstr); document.close(); }  function checkuserinput() { var userinput = document.getelementbyid("textinput").value; var stringtocheckagainst = random_image_array[num].split('.'); //this splits item @ array index array, so. if item "apple.gif", array reads ["apple", "gif"] if (userinput == stringtocheckagainst[0]) {     //user has inputted correct string     window.alert("user gave correct response!"); } else {     //user has inputted incorrect string     window.alert("user gave incorrect response!"); } } </script> <input type="text" placeholder="placeholder text goes here" id="textinput" /> <button type="button" onclick="checkuserinput();">check answer!</button> 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -