簡體   English   中英

如何更改 <input> JavaScript實時顯示字段的VALUE屬性?

[英]How to change an <input> field's VALUE attribute in real time with JavaScript?

我想隨着用戶在另一個輸入字段中鍵入而實時更改輸入字段的值,最好使用常規JS而不是JQuery。

示例:用戶在#input_1中鍵入一個隨機值,並在相同時間#input_2接收用戶鍵入的任何內容並將其設置為其值。

如果用戶從#input_1值中刪除數字,則#input_2跟隨並從其值中刪除相同的數字。

所有這些都是實時的 ,最好不要按下按鈕來觸發執行此操作的功能。

有很多方法可以實現這一點。 這是我的處理方式:

HTML:

<input id="sourceField" />
<input id="destinationField" />

JS:

// When the page is done loading and rendering...
window.addEventListener('DOMContentLoaded', ()=>{
    // Get the appropriate elements
    const sourceField = document.getElementById('sourceField')
    const destinationField = document.getElementById('destinationField')

    // When the user types some input into the first text field...
    sourceField.addEventListener('input', ()=>{
        // Set the value of the destination field to the value of the source field.
        destinationField.value = sourceField.value
    })
})

簡單 ;)

 <input id="input1" onkeyup="document.getElementById('input2').value=this.value" /> <input id="input2" /> 

你可以這樣

您需要選擇(在事件上)第一個輸入,並從該輸入中獲取值,並在第二個輸入中進行更新。

 function handle(e){ var input1 = document.getElementById('input1').value; console.log(input1) document.getElementById('input2').value = input1; } 
 <input id='input1' onkeyup="handle()" value=""/> <input id='input2' value="" /> 

暫無
暫無

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

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