Reputation: 17
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
Upvotes: 1
Views: 8423
Reputation: 801
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;
}
Upvotes: 0
Reputation: 2831
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">
Upvotes: 10
Reputation: 12722
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.
Upvotes: 2
Reputation: 17710
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...
Upvotes: 2