javascript - jQuery drag and drop, validating draggable id -
i've built simple drag , drop activity. when answer dropped on drop area, id stored in variable called 'answer'. when submit button hit runs function called validate checks if variable answer has id of 'correct' stored inside of it.
the problem is, when hit submit button doesn't run validate function because says 'the variable answer not defined'.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>yay drap , drops!</title> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <style> div { height: 100px; width: 100px; border: solid 2px #000; margin: 10px; } </style> <script> $(document).ready(function() { $("#correct").draggable(); //i have drag capability now! $("#wrong").draggable(); //i have drag capability now! $("#droparea1").droppable({ drop: function(event,ui) { var answer = ui.draggable.attr("id"); console.log(answer); } }); }); </script> </head> <body> <div id="correct"> <p>correct answer</p> </div> <div id="wrong"> <p>wrong answer</p> </div> <div id="droparea1"> <p>i'm drop area</p> </div> <script> function validate() { if (answer == ("#correct")) { window.location.replace("www.google.com") //correct! redirect web page next activity } else { window.alert("incorrect, try again") //incorrect, try again } } </script> <button onclick="validate()">submit</button> </body> </html>
one option fix define variable answer
outside of $(document).ready()
scope, this:
var answer = null; $(document).ready(function() { $("#correct").draggable(); //i have drag capability now! $("#wrong").draggable(); //i have drag capability now! $("#droparea1").droppable({ drop: function(event,ui) { answer = ui.draggable.attr("id"); console.log(answer); } });
Comments
Post a Comment