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

JavaScript

jquery 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

Hi 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!

Hey 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:)

$("#story").submit(function (e) {
         var answer = parseInt($(".form-control").val(), 8);

        if (answer != 8) {
          alert("wrong answer"); 
          e.preventDefault();         
        }else {
          alert("right answer");
        }
     })

Hey Gianni,

the datatype is not your problem, because your if condition is not checking for it.

//This does not check for datatype, so "answer" can be a string or an int:
if (answer != 8)

//This would check the datatype, so "answer" can only be an int:
if (answer !== 8)

Are you sure, that the variable "answer" is 8? You could check it like that:

$("#story").submit(function (e) {
  var answer = $('.form-control').val();

  alert(answer);

  if (answer != 8) {
    alert("wrong answer");
    e.preventDefault();
  } else {
    alert("right answer");
  }
});

You need to change

preventDefault();

to

e.preventDefault();