-3

I have this HTML code that I am developing using materialize CSS. However, I cannot currently read the data from the input fields

<form id="two_player">
  <div class="row">
    <div class="input-field col s6">
      <input placeholder="Apelido do jogador 1" id="two_player_one" type="text" class="validate">
      <label for="first_name">Jogador 1:</label>
    </div>
    <div class="input-field col s6">
      <input placeholder="Apelido do jogador 2" id="two_player_two" type="text" class="validate">
      <label for="player_two">Jogador 2:</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col s6">
      <input placeholder="Número de cartas da 1ª rodada" id="two_player_one_round_one" type="number" min="0" max="13" class="validate">
      <label for="player_one_round_one">Rodada 1:</label>
    </div>
    <div class="input-field col s6">
      <input placeholder="Número de cartas da 1ª rodada" id="two_player_two_round_one" type="number" min="0" max="13" class="validate">
      <label for="player_two_round_one">Rodada 1:</label>
    </div>
  </div>
</form>

How do I read each input field with JavaScript?

FZs
  • 16,581
  • 13
  • 41
  • 50
Luiz Gustavo
  • 105
  • 7

2 Answers2

3

You can use getElementById() to find the element, and .value to expose its value.

let two_player_one = document.getElementById('two_player_one').value;
let two_player_two = document.getElementById('two_player_two').value;
let two_player_one_round_one = document.getElementById('two_player_one_round_one').value;
let two_player_two_round_one = document.getElementById('two_player_two_round_one').value;
  • MDN docs for getElementById() here.
aviya.developer
  • 3,343
  • 2
  • 15
  • 41
  • The console doesn't show any value after I press the submit button. newgame.html:488 VM60:140 DomDistiller debug level: 0 If I only use the reference to the tag name it does the html code inside that input field. – Luiz Gustavo Feb 07 '20 at 21:47
1
let val = document.getElementById('an input field ID').value;

    for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
        console.log(document.getElementsByTagName('input')[i].value);
    }

Basically something like this. With the for loop, you loop through all the input elements and console.log() the value (or do whatever you want to with the value). The first one targets an element based on its ID and retrieves the value of it.