Link to home
Start Free TrialLog in
Avatar of tbaseflug
tbaseflugFlag for United States of America

asked on

Swap Input Values

I have a form with 8 text/inputs - what I wanted to try and do - ideally - is to "grab" the value from one input and "drop" them onto another input - so, the two input values would swap places - is that possible - if so how?  I assume jQuery?
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

You'd have to store the value of the first in a temporary variable then reset the value of the first to the value of the second, then set the value of the second to the temporary value.

var in1 = document.getElementById('input1'), in2 = document.getElementById('input2');
var temp = in1.value;
in1.value = in2.value;
in2.value = temp;

Open in new window

Unless the calues are numbers, then you don't need a temp var
//
var a = document.getElementById('input1'), // Assume value = 7
    b = document.getElementById('input2'); // Assume value = 4

a.value = a.value + b.value; // a = 11
b.value = a.value - b.value; // b = 7 (was 4)
a.value = a.value - b.value; // a = 4 (was 7)
//

Open in new window

And by "calues", I, of course, meant "values".
ASKER CERTIFIED SOLUTION
Avatar of Eyal
Eyal
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial