0

I want to compare two strings in JavaScript, but my code isn't working.

I think if(answer==correct_answer_arr[0]) is wrong, but I don't know what the problem is, or how I can fix it.

*I already checked that "correct_answer_arr" has no problem, which has correct information

JS Code:

var correct_answer_arr = new Array();

$('document').ready(function() {
  var str;
  var request = new XMLHttpRequest();
  request.open('get', 'http://localhost:8080/new/text.jsp', true);
  request.onload = function() {
    str = request.responseText;
    correct_answer_arr = str.split(",");
  };
  request.send();
});

function keycheck(event) {
  if (event.keyCode == 13) {
    var answer = $("input").val();
    if (answer == correct_answer_arr[0]) {
      alert("correct");
    } else {
      alert("wrong");
    }
  }
}
6
  • 1
    == will compare strings, what makes you think it is wrong? console.log both values to see if they are what you think they are Commented Sep 4, 2017 at 23:29
  • 1
    also $('document') won't select the document, it is $(document) Commented Sep 4, 2017 at 23:31
  • 1
    Do you only have one <input> on your page? The comparison will be 'wrong' if you don't have a valid answer in $("input").val(). Commented Sep 4, 2017 at 23:31
  • 1
    Are you calling keycheck before the request has returned? Commented Sep 4, 2017 at 23:32
  • 1
    And did you check responseText? Commented Sep 4, 2017 at 23:33

1 Answer 1

2

I would do console.log(correct_answer_arr); before and after the str.split(",") to see what's going on.

Please also check if answer get's set to undefined because it's a common error when calling $().val() on an empty collection. As already mentioned, document is a reserved keyword and should not be written in quotemarks in this case.

Also it's good practice to use === instead of ==.

Sign up to request clarification or add additional context in comments.

1 Comment

i checked everything you said but my codes still doesn't work i think something happens when i get data with ajax.. string which is got with ajax has invisible control character?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.