2010-11-18 78 views
7

如何通過javascript函數訪問HTML文本框?如何從JavaScript訪問HTML文本框?

+0

你的意思是,要獲得文本框的價值? – 2010-11-18 10:00:37

+0

是的。無需返回到服務器,雖然 – 2010-11-18 10:04:39

+0

[更早的線程中的更多方式](http://stackoverflow.com/questions/4206336/how-do-i-use-javascript-to-update-the-values-of-hidden-輸入字段/ 4206459#4206459) – Tobias 2010-11-18 10:07:02

回答

9

設置ID屬性和使用的document.getElementById()函數...下面的例子:

<html> 
<head> 
<script type="text/javascript"> 

function doSomethingWithTextBox() 
{ 
    var textBox = document.getElementById('TEXTBOX_ID'); 
    // do something with it ... 

} 

</script> 
</head> 

<body> 

<input type="text" id="TEXTBOX_ID"> 

</body> 
</html> 
+4

爲簡潔起見,除非調用函數doSomethingWithTextBox(),否則實際上並不會獲得文本框的值(TEXTBOX_ID)。您需要在輸入標記(TEXTBOX_ID)後調用函數doSomethingWithTextBox(),否則doSomethingWithTextBox()將查找尚不存在的文本框,並且您將得到一個錯誤。 – 2010-11-19 01:46:36

4

的document.getElementById( 'textboxid')。值 或 document.formname.textboxname.value

5

給你的文本框的id屬性,之後,用document.getElementById('<textbox id>')它牽回家。在文本框中

5

首先,你需要能夠得到一個DOM(文檔對象模型)參考文本:

<input type="text" id="mytextbox" value="Hello World!" /> 

通知的id屬性,文本框現在有ID mytextbox

下一步是在JavaScript中得到參考:

var textbox = document.getElementById('mytextbox'); // assign the DOM element reference to the variable "textbox" 

這將通過其id屬性檢索HTML元素。請注意,這些ID必須是唯一的,所以不能有兩個具有相同ID的文本框。

現在最後一步是檢索文本框的值:

alert(textbox.value); // alert the contents of the textbox to the user 

value屬性包含文本框的內容,這就是它!

更多的參考,你可能想通過在MDC檢查出一些東西:
GetElementByID Reference
Input Element Reference
A general overview of the DOM

6

很簡單,試試這個:

<!doctype html> 
<html> 
    <head> 
     … 
    </head> 
<body> 
    <form> 
     <input id="textbox" type="text" /> 
    </form> 
    <script> 
     var textboxValue = document.getElementById("textbox").value; 
    </script> 
</body> 

的變量textboxValue將等於wha你已經輸入到文本框中。

請記住,如果在HTML中出現文本框(input字段)後,必須將腳本放在此處,否則當頁面第一次加載時會出現錯誤,因爲該腳本正在查找input字段尚未由瀏覽器創建。

我希望這有助於!