Javascript/HTML DOM: How do I check if text user input equals to string in if statement


I am trying to check in my if statement if the text the user inputs from my html form equals to the string I indicate when submit is clicked. I tried using regular expressions to check if the text is a string, but not sure if done properly. Both if statements end up going straight to the "else alert()" when submit is clicked.

document.addEventListener('DOMContentLoaded', () => {
      const squares = document.querySelectorAll('.grid div')
      const result = document.querySelector('#result')
      const displayCurrentPlayer = document.querySelector('#current-player')
      let currentPlayer = 1
      let colorSubmit = document.getElementById("color");
      colorSubmit.addEventListener('submit', pickColor);

      function pickColor(square) {
        let colorStatus = isColorString(this.player1.value)
        //let x = document.getElementById("player1");
        //var x = document.getElementById("player1").value;
        if (colorStatus === "red") {
          square.classList.add('player-red')
        } else if (colorStatus === "yellow") {
          square.classList.add('player-yellow')
        } else alert('pick "red" or "yellow"')

        let colorStatus2 = isColor2String(this.player2.value)
        //let y = document.getElementById("player2");
        //var y = document.getElementById("player2").value;
        if (colorStatus2 === "blue") {
          square.classList.add('player-blue')
        } else if (colorStatus2 === "black") {
          square.classList.add('player-black')
        } else alert('pick "blue" or "black"')
      }

      function isColorString(player1) {
        const re = new RegExp('[a-z]+');
        return re.test(player1);
      }

      function isColor2String(player2) {
        const re = new RegExp('[a-z]+');
        return re.test(player2);
      }
<form id="color">
  <label for="player1">Player 1 Color:</label>
  <input type="text" id="player1" name="player1"><br><br>
  <label for="player2">Player 2 Color:</label>
  <input type="text" id="player2" name="player2"><br><br>
  <input type="submit" value="Submit">
</form>

Source: JavaSript – Stack Overflow

November 24, 2021
Category : News
Tags: DOM | dom-events | html | javascript | regex

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.