javascript - 如何获取输入类型编号的输入值?
问题描述
我的表单中有一个数字字段,可以在此处输入分数:
<input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please enter a score from 0-100)
在提交表单之前,我需要检查该字段是否已填写。我不想使用required因为我不想在用户需要更多时间来决定输入分数时阻止他们。
我试图抓住总分的价值:
var score = document.getElementsById("total_score").value;
if(score==null){
alert("no score");
}
但似乎不起作用。有任何想法吗?谢谢。
解决方案
让我们详细描述这个问题。我们总是需要在幕后理解问题,这样我们才能解决所有类似的问题。
<div class="score-field">
<label for="total_score">(Please enter a score from 0-100)</label>
<input
type="number"
id="total_score"
name="total_score"
min="0"
max="100"
value="<?php echo $total_score;?>">
</div>
如果我们想抢价值document.getElementById('total_score').value
。它返回一种String
值。
let value = document.getElementById('total_score').value;
console.log(typeof value) //'String'
所以一种String
价值永远不会null
let value = '';
console.log(value == null) //false
讨论够了,对吧?
让我们解决问题。
const score = parseFloat(document.getElementById('total_score').value);
它将值转换String
为Number
.
认为
parseFloat("100"); // 100
parseFloat(''); //NaN
我们可以检查是否value
真的是一个数字。
isNaN(value); // return true or false
我想,这是你的问题解决。
完全解决:
HTML:
<div class="score-field">
<label for="total_score">(Please enter a score from 0-100</label>
<input
type="number"
id="total_score"
name="total_score"
min="0"
max="100">
</div>
JS:
const score = parseFloat(document.getElementById("total_score").value);
if(isNaN(score)){
alert("no score");
}