无法将我的输入值显示在我的函数

时间:2017-12-01 22:30:08

标签: javascript html

我希望我的用法输入一个值,当他们按提交计算时,如果值为null,则应该有一个警告栏预览错误消息。

<form id= "form1"   class = "myform" action ="register.php" method "post">

<label> Loan Amount: </label>                   
<input  type = "text" class= "inputvalues" id = "loanAmm" placeholder = "Fill in the Details"> <br>

<input name = "submit_btn" type ="button"  onclick = "checkvalues();" id = "storevalue" value = "Submit Calculations"> <br>


</form> 

function checkvalues()
{
var loanAmount = document.forms["form1"]["loanAmm"].value;


if (loanAmount == null )
{

    alert("Re-enter value");

    return false; 

}

}

2 个答案:

答案 0 :(得分:0)

您的测试应该是:

if (loanAmount === '') {
    alert("Re-enter value");
    return false; 
}

如果输入为空,则该值不为空但为空。

答案 1 :(得分:0)

使用document.forms [&#34; form1&#34;],&#34; form1&#34;引用元素时是表单的名称,而不是id。 document.forms [&#34; form1&#34;] [&#34; loanAmm&#34;] - &#34; loanAmm&#34;是输入的名称。

最佳做法是使用id引用输入。

另外,使用 addEventListener 添加onclick处理程序,因为它将逻辑与布局分开。

&#13;
&#13;
document.getElementById("storevalue").addEventListener("click", function() {
  var loanAmount = document.getElementById("loanAmm").value;

  if (loanAmount.trim() === "") {

    alert("Loan amount cannot be blank");

    return false;

  } else {
    document.getElementById("form1").submit();
  }

});
&#13;
<form id="form1" class="myform" action="register.php" method "post">

  <label> Loan Amount: </label>
  <input type="text" class="inputvalues" id="loanAmm" placeholder="Fill in the Details"> <br>

  <input name="submit_btn" type="button" id="storevalue" value="Submit Calculations"> <br>


</form>
&#13;
&#13;
&#13;