2014-03-25 31 views
0

我希望將輸入框鏈接起來,以便當您在其中輸入某些內容時,它會顯示在另一箇中(反之亦然)。這裏有一個「codepen」,顯示了我目前的工作情況。有沒有更好的方法來「鏈接」文本輸入?

http://codepen.io/anon/pen/yEAbk/

這很簡單,但我覺得應該做到這一點更簡單的方法。我在codepen中說明的這種方法也有問題。您會注意到用一個字符串填充其中一個框的按鈕。即使內容已更改,「onchange」事件也不會運行,因此其他輸入框不會更新。

有沒有更簡單的方法來做到這一點,將解決我一直有的問題?

+0

它做工精細,而且代碼是很短的,簡單 – Rex

+0

onChange事件只在用戶輸入火災,你應該感到高興。當代碼設置輸入時,通常不希望事件觸發,只有當用戶執行時纔會觸發事件。 – bitfiddler

回答

4

這正是那種問題databinding是要解決。有很多圖書館,但目前最流行的是AngularJS(谷歌)。 http://angularjs.org/

觀看演示:http://jsfiddle.net/34ZCs/2/兩個輸入綁定變量yourName

<div ng-app> 
    <div>  
     <input type="text" ng-model="yourName" placeholder="A"> 
     <input type="text" ng-model="yourName" placeholder="B"> 
    </div> 
</div> 
+1

使用angular,您可以使用零行自定義JavaScript來完成。如上圖所示,您可以僅用您的視角來完成它。很酷! – frosty

+0

這太好了。正如你可能猜到的那樣,我真的很陌生。直到現在我甚至都不知道什麼是圖書館,所以我不確定代碼中發生了什麼,或者如何讓它工作(在jsfiddle之外)...我是否必須下載AngularJS? – user3220404

+0

@ user3220404是的只需按照主頁上的演示:http://angularjs.org/ – basarat

0

使用 「的onkeyup」 而不是 「平變化」。然後下一個文本框會立即更新。

做這樣的事情

<input type="text" name="a" id="a" onkeyup="fillBoth('a','b')" onfocus="fillBoth('a','b')" /> 
<input type="text" name="b" id="b" onkeyup="fillBoth('b','a')" 
onfocus="fillBoth('a','b')"/> 
<button type="button" id="clicky" onclick="fillWithX()">click here for xxx</button> 

你的JavaScript應該這樣被更新。

function fillWithX() { 
    document.getElementById('a').value = 'xxx'; 
    document.getElementById('a').focus(); 
} 
0

你的事件處理程序的輕微變化可能會訣竅。請看:http://codepen.io/anon/pen/budnp/

<input type="text" name="a" id="a" onchange="fillBoth('b', 'a');" /> 
<input type="text" name="b" id="b" onchange="fillBoth('a', 'b');" /> 
<button type="button" id="clicky" onclick="fillWithX()">click here for xxx</button> 

和腳本:

function fillBoth(copyTo, copyFrom) { 
    document.getElementById(copyTo).value = document.getElementById(copyFrom).value; 
} 
相關問題