Search code examples
javascripthtmljquerytypeerrorvar

Error with Javascript TypeError code, variable undefined


I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.

It then compares that elements value (using jQuery) with the value of the input where the function is wrong It brings up an error saying:

TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)

Any help would be appreciated. Thanks (UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)


EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.

      function textVerify(item) {
          var word= document.getElementById(($('#questionNumber').text()+'a'));
      if (item.value.toUpperCase() === word.toUpperCase()){
          item.style.color = "green";
          $( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
          main()
          } else {
              item.style.color = "black";
        }
          <span class="ihide" id="questionNumber"></span>
          <p id="1a" class="ihide">Seven</p>
          <input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">


Solution

  • The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.

    function textVerify(item) {
    
      var word = document.getElementById(($('#questionNumber').text() + 'a'));
    
      if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
        item.style.color = "green";
        $(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
        //main()
      } else {
        item.style.color = "black";
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <span class="ihide" id="questionNumber">1</span>
    <p id="1a" class="ihide">Seven</p>
    <input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">