将变量从PHP传递给JS检查是否为null

时间:2019-01-30 19:52:02

标签: javascript php

我正在使用PHP post方法将变量发送到表单。我将变量从PHP转移到JavaScript。当我创建一个nullcheck时,即使该框保留为空,也不会显示为null。我想知道如何使用此方法正确创建一个nullcheck。我认为文本框会将变量设置为类似于我不知道的空格,但是我不确定如何将其设置为null而不是小值

enter code here
//This is the form's code

<!DOCTYPE html>
<style>
table, th, td{
    border: 5px solid purple;
    border-collapse: collapse;
}

</style>
<form method="POST" 
action="http://www.timmcc.com/willmargulies/hwc.php">
<table style="width:100%">
<tr>
    <th style="width:25%:">Weighting (write without percents)</th>
    <th style="width:75%">Assignment Grades (Leave empty if none)</th>
</tr>
<tr>
<td><input type="text" name="weight" id="weight" width="100%"></td>
<td><input type="text" name="a1" id="a1" width="25%"/>
    <input type="text" name="a2" id="a2" width="25%"/>
    <input type="text" name="a3" id="a3" width="25%"/>
    <input type="text" name="a4" id="a4" width="25%"/> </td>

<td> </td>
</tr>

</table>
<input type="submit"/>
</form>

//The php receiving page starts here

<!DOCTYPE html>
<p id="demo">Loading...</p>
<script>
assnum = 0;
find();
function find(){
var weighta = "<?php echo $_POST["weight"] ?>"; 
var a1a = "<?php echo $_POST["a1"] ?>";
var a2a = "<?php echo $_POST["a2"] ?>";
var a3a = "<?php echo $_POST["a3"] ?>";
var a4a = "<?php echo $_POST["a4"] ?>";
var weight = parseInt(weighta)/100;
alert(weight);
var a1 = parseInt(a1a);
var a2 = parseInt(a2a);
var a3 = parseInt(a3a);
var a4 = parseInt(a4a);
if(a1 === undefined){
alert("Please put your first grade in the leftmost box.\nOr put in a 
grade in general.")
//doesn't work 
}


}







 document.getElementById("demo").innerHTML = fingrade;
 </script>




 </script>

1 个答案:

答案 0 :(得分:0)

如果您解析一个空字符串,它将返回NaN。

因此,而不是

if(a1 === undefined)

尝试

if(isNaN(a1))