PDA

View Full Version : JavaScript Alteration Help



Croc
Mar 6th, 2007, 10:42 PM
Hi, my first post.
Came across these forums while searching for help on a specific JavaScript problem.

Back in 2005, a member of these boards posted a reply to a thread that was almost exactly what I was after, but it needs a little alteration. Tried to PM him first, but haven't had a reply.

The Problem:

Below is a piece of code that takes the last 4 characters from form field1 and inputs them into field2 in the same form on the fly. Thing is, it only works on the stated length for field1, for instance, the code below is set for 10 characters max.


<script language="javascript" type="text/javascript">
<!--
function RetrieveNumber( field2, field1 )
{
var extract = field1.value;
var start = 6;
var end = 10;
var hold;
hold = extract.substring( start, end );

field2.value = hold;
}
//-->
</script>

Not knowing much at all about JavaScript, I gave it a go and tried to add an else if statement in there to try and get it to accept different lengths input into field1.


<script language="javascript" type="text/javascript">
<!--
function RetrieveNumber( field2, field1 )
{
var extract = field1.value;
{
if (field1.value = 10)
{
var start10 = 6;
var end10 = 10;
var hold;
hold10 = extract.substring( start10, end10 );

field1.value = extract;
field2.value = hold10;
}
else if (field1.value = 14)
{
var start14 = 10;
var end14 = 14;
var hold;
hold14 = extract.substring( start14, end14 );

field1.value = extract;
field2.value = hold14;
}
}
}
//-->
</script>

Have tried various combinations of the above, but that is the latest attempt.
The above still works, but only with the top if statement, i.e. if the string from field1 is 10 characters, it'll extract the last 4 characters 6 - 10 correctly, but if the string is 14 characters long, it still only extracts the characters 6 - 10

The string lengths that will be used will range from 4 to 14 characters in length.

Probably looks like a load of garbage that I just wrote, but from it hopefully you can see what I'm trying to achieve.

chump2877
Mar 6th, 2007, 11:56 PM
See if this does what you want:


<p>Type something into Field 1. When focus is taken away from Field 1, the last 4 characters of Field 1's value are inserted into Field 2.</p>

<p>Field 1: <input type="text" id="field1" onblur="getChars(this,'field2');" /></p>
<p>Field 2: <input type="text" id="field2" /></p>


<script type="text/javascript">

function getChars(txtObj1,id)
{
if (txtObj1.value == "") return false;

var charArr = txtObj1.value.split("");
var output = "";

for (i=txtObj1.value.length-4; i<txtObj1.value.length; i++)
output += charArr[i];

document.getElementById(id).value = output;
}

</script>

Croc
Mar 7th, 2007, 12:06 AM
Perfect, thank you very much :)