2015-11-06 32 views
1

的點擊顯示值按鈕我用一個文本框,代碼:HTML - 在文本框

<input type = "text" size = "2" maxlength = "2" name = "myname"> 

和一個按鈕:

<button type = "button" onclick = "alert('Clicked!')">Print</button> 

現在,當我點擊它,消息/警報彈出說Clicked!。我怎樣才能讓它顯示文本字段上的任何值呢?泰

回答

2

嘗試這種解決方案:

<input type="text" id="test" size="2" maxlength="2" name="myname"> 
<button type="button" onclick="alert(document.getElementById('test').value);">Print</button> 

的工作例如,你可以在這裏找到:http://jsfiddle.net/sebastianbrosch/x8zzvd5s/

說明
你有一個ID添加到您的文本字段(這裏test)。在alert()上,您可以通過document.getElementById('test').value獲得文本字段的值。

+0

嗨,謝謝你的回答!工作正常,我接受了。我得到的最後一個問題是,如果我必須聲明一個id如圖所示,那麼名稱代表什麼?再次感謝您的幫助(我是html新手) – darkchampionz

+1

這個名字用於'POST'。如果您使用PHP來獲取由表單發送的這些字段,可以使用'$ _POST ['myname']'獲取值。 –

1

,如果你這樣做是爲了打印使用PHP一個人的名字什麼的話,應該是這樣的: 到HTML的身體補充一點:

<form name="form1" action="registration.php" method="POST" onsubmit="myFunction()" > 
<input type="text" name="name" id="name"> 
<input type="submit" value="submit"> 
</form> 

您可以使用上提交的JavaScript驗證這一領域如:(HTML中的頭標記寫)

<script> 
    var name=document.getElementById("name").value; 
    myFunction() 
    { 
    if(name!="") 
     { 
    return true; 
     } 
     else 
     { 
    //show alert. 
    return false; 
     } 
     } 
      </script> 

在PHP中,你可以通過(reg.php)打印文本輸入的名稱用戶:

<?php 
    $name=$_POST['name'];//it is the name of the control field 
    echo $name; 
?>