簡體   English   中英

用javascript交換2個文本框中的值

[英]Swap values in 2 textboxes with javascript

我正在制作一個帶有 4 個輸入 a、b、c 和 d 的簡單計算器,並且需要能夠交換 c 和 d 的值。 例如,文本框 c 的值為 45,文本框 d 的值為 75。單擊一個按鈕來交換值,因此 c=75 & d=45

完整的 Javascript 示例

Javascript :

function swapValues(){
var tmp = document.getElementById("c").value;
document.getElementById("c").value = document.getElementById("d").value;
document.getElementById("d").value = tmp;

}

和 HTML :

<input type="text"  id="a" value="1st" />
<input type="text"  id="b" value="2nd" />
<input type="text"  id="c" value="3rd" />
<input type="text"  id="d" value="4th" />
<input type="button"  id="go" onclick="swapValues()" value="Swap">

如果您使用 jQuery,並且您的輸入具有正確的 id,則應該這樣做:

var t = $('#c').val();
$('#c').val($('#d').val());
$('#d').val(t);

不過,這很微不足道……

我假設你的 HTML 看起來像這樣:

<input id="input-c">
<input id="input-d">

如果你使用jQuery (我推薦它),你可以這樣做:

var temp = $("#input-c").val();
$("#input-c").val($("#input-d").val());
$("#input-d").val(temp);

如果你願意,你可以稍微優化一下,但它增加了幾行:

var $inputC = $("#input-c");
var $inputD = $("#input-d");
var temp = $inputC.val();
$inputC.val($inputD.val());
$inputD.val(temp);

如果您不使用 jQuery,您可能會執行以下操作:

var inputC = document.getElementById("input-c");
var inputD = document.getElementById("input-d");
var temp = inputC.value;
inputC.value = inputD.value;
inputD.value = temp;

通常,這是交換兩個變量值時的常見編程模式。 您必須先創建一個臨時變量,然后才能進行交換,否則一個變量會破壞另一個變量。

使用 Vanilla javascript 的概念可能是這樣的......

HTML

<input type="text" placeholder="od" class="firstInput" />
<input type="text" placeholder="do" class="secondInput" />
<span class="inputExchange">
    <i class="fas fa-exchange-alt float-right"></i>
</span>

JavaScript:

let firstInput = document.querySelector(".firstInput");
let secondInput = document.querySelector(".secondInput");
let temp;
let inputExchange = document.querySelector(".inputExchange");
inputExchange.addEventListener("click", exchangeValue);

function exchangeValue() {
  temp = firstInput.value;
  firstInput.value = secondInput.value;
  secondInput.value = temp;
}

暫無
暫無

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

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