简体   繁体   中英

Swap values in 2 textboxes with javascript

I'm making a simple calculator with 4 inputs a,b,c & d and need to have the ability to swap the values of c & d. For example textbox c has a value of 45 & textbox d has a value of 75. A button is clicked which swaps the vales so c=75 & d=45

Full Javascript Example

Javascript :

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

}

and 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">

If you use jQuery, and your inputs have the right ids, this should do:

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

It's quite trivial, though...

I'm assuming your HTML looks something like this:

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

If you're using jQuery (I'd recommend it), you might do it like this:

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

You could optimize this a little bit if you wanted, but it adds a couple of lines:

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

If you're not using jQuery, you might do something like this:

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

In general, this is a common programming pattern when swapping the value of two variables. You have to make a temporary variable before you can do the swapping, otherwise one variable will clobber the other.

The concept could be like this using 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM