Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Gianni Zamora
9,547 Pointsjquery function help
so I am trying figure out the correct way of building this form so that when a number = anything different than 8 it alerts'wrong anser' and prevents the form from submitting. I think I almost have it completed but i input the number 8 and it says "wrong answer " and continues to submit form
var answer = $('form-control').val();
$("#story").submit(function (e) {
if (answer != 8) {
alert ("wrong answer");
preventDefault();
}else {
alert("right answer");
}
})
2 Answers
Chris Shaw
26,676 PointsHi Gianni,
Along with what Torben Ewert mentioned you have your answer value stored outside the submit which will result in the same value for every submit as it only keeps the original value of the input field and not any subsequent changes later on, instead you would want to have this variable inside the submit even so you get the correct value each time.
$("#story").submit(function (e) {
var answer = $('form-control').val();
if (answer != 8) {
alert("wrong answer");
e.preventDefault();
} else {
alert("right answer");
}
});
Happy coding!
Torben Ewert
3,172 PointsYou need to change
preventDefault();
to
e.preventDefault();
Gianni Zamora
9,547 PointsGianni Zamora
9,547 PointsHey Chris, Thank you but I tried what you showed me to do and i still get an error saying it is a wrong answer. Do you think it is because It is pulling a string of "8" instead of the numerical value of 8? If that is that case, how would i do it so it converts it to an integer. I have updated the code allitle if you can help me please:)
Torben Ewert
3,172 PointsTorben Ewert
3,172 PointsHey Gianni,
the datatype is not your problem, because your if condition is not checking for it.
Are you sure, that the variable "answer" is 8? You could check it like that: