Thursday, September 23, 2010

JavaScript: Switch values in form fields

I have two text fields in a form - "foo" and "bar", and I wanted to add a button to easily switch the values, so that "foo" becomes "bar" and vice versa. This is my JavaScript approach on how to do this:

function switchas() {
var oldFoo = document.getElementById('foo');
var oldBar = document.getElementById('bar');
oldFoo = oldFoo.value;
oldBar = oldBar.value;
document.myForm.elements["foo"].value = oldFoo;
document.myForm.elements["bar"].value = oldBar;
// Uncomment following line for autosubmit
// document.myForm.submit();
}

And the HTML looking like this:

<a href="#" onclick="switchas();">Switch</a>
<form action="#" method="post" name="myForm">
<input id="foo" name="foo" value="foo" type="text">
<input id="bar" name="bar" value="bar" type="text">
</form>

No comments:

Post a Comment