簡體   English   中英

我如何使我的JavaScript讀取表單值?

[英]how can i make my javascript to read the form value?

我正在嘗試做一個表格,允許用戶單擊按鈕后看到他在字段中輸入的詳細信息。 由於某些原因,javascript無法讀取用戶放入表單中的文本的值。 有什么幫助嗎?

<form>
first name:
<input type="text" autofocus autocomplete="on" placeholder="first name" required  id="first">
last name:
<input type="text" autocomplete="on" placeholder="last name" required  id="last">
year of birth:
<input type="number" pattern="^[0-9]{4}" id="year">
gender:
<select id="sel">
<option selected>MALE</option>
<option>FEMALE</option>
</select>
<button id="butt">click</button>

</form>

javascript:

function cont(){
    function person()
{
    this.FirstName = null;
    this.LastName = null;
    this.YearOfBirth = null;
    this.Gender = null;
    this.Weight = null;
    this.Height = null;
    this.Country = null;
    this.FullName = function()
    {
    return this.FirstName + " " + this.LastName 
    };
    this.Age = function()
    {
        var today = new Date();
        var yy = today.getFullYear();
        return yy - this.YearOfBirth;
    };
    this.toString = function()
    {
    return "this rider lives in " + this.Country + " and his name is " + this.FirstName + " " + this.LastName;  
    };  
}

var rider = new person
rider.FirstName = document.getElementById('first').value
rider.LastName = document.getElementById('last').value
rider.YearOfBirth = document.getElementById('year').value
rider.Gender = document.getElementById('sel').value

document.getElementById('butt').onclick = function()
{

if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
{
    alert ("fill all the required fields")
}
else
{
document.write(rider.FirstName + "<br>")
document.write(rider.LastName + "<br>") 
document.write(rider.YearOfBirth + "<br>")
document.write(rider.Gender + "<br>")
document.write(rider.FullName() + "<br>")   
}


} }

您正在設置“騎手”。 頁面加載時的值(它們為空),但是當用戶單擊按鈕時不再獲取它們。 因此, document.write函數只是寫入空值。 嘗試:

document.getElementById('butt').onclick = function()
{

  rider.FirstName = document.getElementById('first').value;
  rider.LastName = document.getElementById('last').value;
  rider.YearOfBirth = document.getElementById('year').value;
  rider.Gender = document.getElementById('sel').value;

  if (rider.FirstName != typeof ("hello") || rider.LastName != typeof("hi") || rider.YearOfBirth == isNaN)
  {
    alert ("fill all the required fields");
  }
  else
  {
    document.write(rider.FirstName + "<br>");
    document.write(rider.LastName + "<br>");
    document.write(rider.YearOfBirth + "<br>");
    document.write(rider.Gender + "<br>");
    document.write(rider.FullName() + "<br>");   
  }


} }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM