I’m making a web application for a class which contains a jsp file that uses jquery. I want the app to trigger an alert right before submitting. This works some of the time in my real program, and other times the alert is never triggered. I can’t seem to peg down an instance where it always works or never works. My error console is silent on the matter, unless I add Firebug breakpoints. Then it gives me
Error: attempt to run compile-and-go script on a cleared scope
Source File: http://code.jquery.com/jquery-1.7.2.min.js
Line: 2
But I have no idea what that means. As far as Firebug goes, I can’t understand why the evaulation stops before the alert message.
I tried to make an sscce documenting the problem, but I guess it was too different from my real program, because submit never worked. I’ll show some code from my real program. (Sorry about the lack of SSCCE.)
$(document).ready(function() {
$("#questionDisplay").submit(function() {
var correctAnswer = $(".correctAnswer").attr("value");
var answer = "";
if ($(".multipleChoice").length > 0) {
answers = $("input:checked");
for (var obj in answers) {
answer += obj.attr("value") + "#";
}
} else if ($(".fillBlank").length > 0) {
for (var answerNo = 1; $(".answer" + answerNo).length > 0; ++answerNo) {
answer += $(".answer" + answerNo).attr("value") + "#";
}
} else {
answer = $(".answer1").attr("value");
}
if (answer == correctAnswer) {
alert("Yes! Correct!");
} else {
alert("Sorry, incorrect.");
}
});
});
The jsp is a huge mess (we have to use scriplets 🙁 ), but if you’d like to see it just lemme know.
How do I get my submit handler to work every time?
In your example,
answersis a jQuery collection of elements. Looping through it usingfor(var obj in answers) { }is actually looping through the properties of answers, not the elements themselves. Therefore, calling .attr() on a property is not going to work.In general, if I see my debugger state that jQuery has an error, it’s 99.9% of the time me calling a jQuery method on a non-jquery selected object. In this case, I saw the error in Chrome’s JavaScript console, and sometimes results may vary with different consoles.
A good practice is to prefix variables that store jQuery elements with $ to indicate that they are jQuery objects. For instance,
$answersmakes it easier to keep track of what it contains.Use:
Instead of this: