DIV CSS 佈局教程網

用 JS 讓輸入框預先帶入 value 預設值
編輯:關於JavaScript     

有個常見需求:頁面上有兩個輸入框,希望打開頁面時,第二個輸入框(trueprice)的值預設就等於第一個(price2)的值;而當使用者在第一個框輸入時,第二個框也要即時同步。同時,第二個輸入框的 HTML 標籤是固定不可修改的。該怎麼做到呢?

先看原本的結構:

 <input type="text" id="price2" value="333"/> <input type="text" id="trueprice" value="" />

原本只有監聽輸入事件:

 <script type="text/javascript"> document.getElementById("price2").onkeyup = function() { document.getElementById("trueprice").value = this.value; } </script> 

問題是:這樣做的話,頁面一打開時 trueprice 仍是空的,因為同步只在「輸入後」才觸發。要讓它「一載入就同步」,只要在頁面載入時主動把 price2 的值複製給 trueprice 一次即可。以下是我的實作:

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>Test</title> </head> <body> <input type="text" id="price2" value="333" onkeyup="test(this.value);"/> <input type="text" id="trueprice" value="" /> <script type="text/javascript"> var price2 = document.getElementById("price2").value; document.getElementById("trueprice").value = price2; function test (defaultVal) { document.getElementById("trueprice").value = defaultVal; } </script> </body> </html> 

效果如下圖:


關鍵在於那段直接寫在 script 中的初始化程式:在頁面載入時先讀取 price2 的初始值,並立刻賦值給 trueprice;接著再透過 onkeyup 呼叫 test 函式處理後續的即時同步。如此一來,即使 trueprice 的 HTML 標籤保持不動(value 固定為空),也能透過 JavaScript 在載入時動態帶入預設值,並在輸入時持續同步。第一個文本框輸入的內容能即時反映到第二個文本框。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved