JavaScript擷取/更改文字框的值

來源:互聯網
上載者:User

儘管<input type="text" />和<textarea />是不同元素,但它們均支援同樣的特性來擷取包含在文字框內的文本。考慮以下例子:

<html>
<head>
<title>Retrieying a Textbox Value Example</title>
<script type="text/javascript">
function getValues(){
var oTextbox1=document.getElementById("txt1");
var oTextbox2=document.getElementById("txt2");
alert("The value of txt1 is ""+oTextbox1.value+""n"+
"The value of txt2 is"" +oTextbox2.value+""");
}
</script>
</head>
<body>
<input type="text" size="12" id="txt1" /><br/>
<textarea rows="5" cols="25" id="txt2"></textarea><br />
<input type="button" value="Get Values" onclick="getValues()"/>
</body>
</html>

這個例子顯示了兩個文字框,一個是單行的另一個是多行的,還有一個按鈕。當點擊按鈕時,會出現警告框顯示各個文字框中的內容。

 

也可以在兩個文字框中輸入一些內容,然後點擊按鈕。
 

因為value特性是個字串,可以使用任何字串的特性和方法。例如,可以使用length特性來擷取文字框中的文本長度:

<html>
<head>
<title>Retrieving a Textbox Length Example</title>
<script type="text/javascript">
function getLengths(){
var oTextbox1=document.getElementById("txt1");
var oTextbox2=document.getElementById("txt2");
alert ("The length of txt1 is "+oTextbox1.value.length+"n"
+"The length of txt2 is" +oTextbox2.value.length);
}
</script>
</head>
<body>
<input type="text" size="12" id="txt1"/><br />

<textarea rows="5" cols="25" id="txt2"></textarea><br />
<input type="button" value="Get Lengths "onclick="getLengths()" />
</body>
</html>

 

這個例子中使用value的length特性來判斷每個文字框中的字元數。


這個value特性也可用於給文字框設定新內容:

<html>
<head>
<title>Changing a Textbox Value Example</title>
<script type="text/javascript">
function setValues(){
var oTextbox1=document.getElementById("txt1");
var oTextbox2=document.getElementById("txt2");
oTextbox1.value="fitst textbox";
oTextbox2.value="second textbox";

}
</script>
</head>
<body>
<input type="text" size="12" id="txt1" /><br />
<textarea rows="5" cols="25" id="txt2"></textarea><br />
<input type="button " value="Set Values" onclick="setValues()" />
</body>
</html>


這個例子中,點擊按鈕可將第一個文字框設定為"first textbox",將第二個文字框設定為"second textbox"。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.