김진오
김진오

Reputation: 79

How to compare strings in JavaScript

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");
    }
  }
}

Upvotes: 0

Views: 103

Answers (1)

ledicjp
ledicjp

Reputation: 40

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 ==.

Upvotes: 2

Related Questions