Javascript - 无法读取undefined的属性'trim'

时间:2017-06-20 09:59:54

标签: javascript html firebase firebase-realtime-database

这是我在网站上创建的表单。我需要获取输入值。

<div id="addPlayerForm" style="display:none;">  
  <form>
                <input class="my-input" type="text" placeholder="Name" 
                id="player_name"></input>
                </br>
                <input class="my-input" type="text" 
                placeholder="Position" id="player_position" 
                style="text-transform:uppercase;"></input>
                </br>
                <input class="my-input" type="number" 
                placeholder="Rating" id="player_rating"></input>
                </br>
                <button class="waves-effect waves-light btn" 
                style="background:#01579B;margin-bottom:3rem;" 
                onClick="pushPlayer()">Add Player</button>
 </form>
</div>

这是pushPlayer()函数: 在这里,我使用getElementById从输入中获取值。并且name.value也未定义!而且我认为trim()不起作用,因为值未定义。但我不知道哪里出错了。

function pushPlayer() {
var name = document.getElementById('player_name');
console.log(name.value);
if (document.getElementById("player_name").value.trim() !== '' && 
document.getElementById("player_position").value.trim() && 
document.getElementById("player_rating").value.trim() !== '') {
    var playerName = document.getElementById('player_name').value;
    var playerPosition = 
document.getElementById('player_position').value;
    var playerRating = document.getElementById('player_rating').value;
    firebase.database().ref('playersList/').push({
        Name: playerName,
        Position: playerPosition,
        Rating: playerRating
    });
    Materialize.toast('Player Added to the database', 500);
} else {
    Materialize.toast('Type the Details Dude ;)', 1000);
}

document.getElementById("player_name").value = '';
document.getElementById("player_position").value = '';
document.getElementById("player_rating").value = '';
document.getElementById("player_name").focus();
}

这是我得到的错误:

Uncaught TypeError: Cannot read property 'trim' of undefined
at pushPlayer (script.js:312)
at HTMLButtonElement.onclick ((index):409)
pushPlayer @ script.js:312
onclick @ (index):409

我的错误在哪里? 有人可以帮帮我吗?

0 个答案:

没有答案