Quote:
|
Originally Posted by Oli-G
Thanks mate, I initially envisaged it would be a bit leaner, ie just call on the text property of box a to equal that of box b, and vice versa.
|
That wouldn't have worked because by time you come to make the value of field B equal that of field A, the value of field A has already been replaced with the value from field B, as per the first statement.
Consequently, you need to temporarily store both values before changing either.
You follow?
Quote:
Because I need to then somehow have a second button that, if numbers are entered, swaps the values in the box from smalles to largest, top box to bottom, and it might be a bit over me with that method!
Is there a leaner way, or could that be used for both?
Thanks again
|
Here's basically what the following function does…
- Identify the relevant text field and creates an array of their identities according to the order in which they appear in the markup
- Creates an array for the values and matches each value to a position in the array.
- Sorts the values array alpha-numerically (done using the sort() method).
- Loops through the target text fields from top to bottom (first to last) putting in the values as they appear in the newly sorted values array. i.e placing the first alpha-numerical value into the first text field, the second alpha-numerical value into the second field, etc…
another basic e.g.
js:
Code:
function sortVals() {
// 1
fieldObjs = document.getElementById('thesefields').getElementsByTagName('input');
// 2
targetFieldsArray = new Array();
for (i=0; i<fieldObjs.length; i++) {
targetFieldsArray[i] = fieldObjs[i].value;
}
// 3
targetFieldsArray.sort();
// 4
for (i=0; i<fieldObjs.length; i++) {
fieldObjs[i].value = targetFieldsArray[i];
}
}
markup:
Code:
<span id="thesefields">
<input type="text" value="8" /><br />
<input type="text" value="zebra" /><br />
<input type="text" value="3" /><br />
<input type="text" value="alpha" />
</span>
<input type="button" value="sort" onclick="sortVals()" />