Search code examples
javascripthtmltic-tac-toe

Javascript - How to have the name of the players with queryselector?


I create a system to have the names of the players how get the 2 values of the names

I create 2 input text and I want take the 2 values to show the name's players but I can not:

HTML:

<section id="first_section" class="first_section">
  <input type="text" placeholder="Nom du premier joueur" style="color: blue; font-size: 120px;" size="500" id="firsttext"><br>
  <button type="button" id="first_button">Suiva`enter code here`nt ></button>
</section>

<section id="second_section" class="second_section">
  <input type="text" placeholder="Nom du deuxième joueur" style="color: blue; font-size: 120px;" size="500" id="secondtext"><br>
  <button type="button" id="second_button">Suivant ></button>
</section>

JavaScript:

var firsttext = [document.querySelector("#firsttext").element, document.querySelector("#secondtext").element];


if (!estValide(this))
  {
    afficheur.sendMessage("Case occupée ! <br />Joueur " + firsttext[tour] + " c'est toujours à vous !");

  }

Solution

  • The shorter and cleaner way to do this is to use a single button to check and retrieve both the input values then assign the retrieved values to your firsttext array like this:

    /* JavaScript */
    
    var btn = document.querySelector("button");
    var firsttext = [];
    
    btn.addEventListener("click", function(){
      var player1 = document.getElementById("firsttext");
      var player2 = document.getElementById("secondtext");
      
      if (player1.value != "" && player2.value != "") {
        firsttext.push(player1.value);
        firsttext.push(player2.value);
        alert(firsttext);
        return firsttext;
      } else {
      	alert("Enter players' names");
      }
    	
    });
    <!-- HTML -->
    
    <section id="first_section" class="first_section">
      <input type="text" placeholder="Nom du premier joueur" id="firsttext"><br>
    </section>
    <p></p>
    <section id="second_section" class="second_section">
      <input type="text" placeholder="Nom du deuxième joueur" id="secondtext"><br>
    
    </section>
    
    <section id="button">
        <button type="button" id="second_button">Suivant ></button>
    </section>