簡體   English   中英

如何在一個文本字段中輸入的文本實時復制到多個文本字段?

[英]How can I get text entered in one text field copied in realtime to multiple text fields?

到目前為止,這是我鏡像(復制數據)另一個文本字段的內容,但是我想在多個(四個以上)字段中執行此操作:

<script type="text/javascript">
    function copyData(from,to) { to.value = from.value; }
</script>

<input type="text name="Company_Name__1" autofocus="focus" value="" size="20" required 
onChange="copyData(this,document.Broker_Opportunity.Company_Name__15)" onKeyUp="copyData(this,document.Broker_Opportunity.Company_Name__15)">

<input type="text" name="Company_Name__15" value="" size="20" required
onChange="copyData(this,document.Broker_Opportunity.Company_Name__1)" onKeyUp="copyData(this,document.Broker_Opportunity.Company_Name__1)">

您可以使用元素ID數組作為參數。 像這樣

copyData(this, ['id1', 'id2']);

然后,您應該在for循環上迭代該數組,並使用document.getElementById來獲取元素並復制值。

如果要保持相同的結構:

function copyData(from,to) {
    to.value = from.value;
}

那么合理的to值將必須是多個值。 這意味着一個數組。 像這樣:

function copyData(from,to) {
    for (var i = 0; i < to.length; i++) {
        to[i].value = from.value;
    }
}

然后,要使用此功能,只需將其傳遞給數組而不是單個元素:

<input type="text name="Company_Name__1" autofocus="focus" value="" size="20" required
       onChange="copyData(this,[document.Broker_Opportunity.Company_Name__15, document.someOtherElement])"
       onKeyUp="copyData(this,[document.Broker_Opportunity.Company_Name__15, document.someOtherElement])">

為了簡化您的HTML代碼,請使用公共class值來標識目標文本字段:

HTML代碼:

<input type="text name="Company_Name__1" autofocus="focus" value="" size="20" required
       onChange="copyData(this,'your_class')"
       onKeyUp="copyData(this,'your_class')">

JS代碼:

    function copyData(from, dest_class) {
        var toArr = document.getElementsByClassName(dest_class);
        for (var i = 0; i < toArr.length; i++) {
            toArr[i].value = from.value;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM