Scott said:
I need to write a function that copies variables to fields. I've used an
array and loop because it's neater than writing a similar sentence out
10 times.
var myString = new
String("id,callername,address,phone,phoneb,email,sqft,source,action,status");
var myFields = myString.split(',');
It seems a bit pointless to create a string purely for the sake
of then creating an array. Why not just create an array?
var myFields = [
'id','callername','address','phone',
'phoneb','email','sqft','source',
'action','status'
];
//myValues is an array of values passed to the function
var myValues =
[id,callername,address,phone,phoneb,email,sqft,source,action,status];
whatever was passed has now obliterated by re-initialising the
variable. It isn't good to have an input element called 'id',
it will be easily confused with the id attribute and may cause
issues.
You should have something like:
function theFuntion() {
....
And call it with (presuming the values are passed as strings):
theFunction('anId','aCallername','anAddress','aPhone',
'aPhoneB','anEmail','aSqft','theSource',
'theAction','theStatus');
...
now use the arguments collection to get at the values passed to
the function. Or, you can pass an array:
function theFuntion(myValues) {
....
var myData = ['anId','aCallername','anAddress','aPhone',
'aPhoneB','anEmail','aSqft','theSource',
'theAction','theStatus'];
theFunction(myData);
...
You should also pass a reference to the form to make life
easier:
function theFuntion(theForm, myValues) {
....
var myData = ['anId','aCallername','anAddress','aPhone',
'aPhoneB','anEmail','aSqft','theSource',
'theAction','theStatus'];
theFunction(this.form, myData);
...
for(var i=0;i<myFields.length;i++) {
document.formname.myFields.value=myValues;
}
Try this:
<script type="text/javascript">
function addValues(f, myValues){
var myFields = ['Id','callername','address','phone',
'phoneb','email','sqft','source','action','status'];
for(var i=0, len=myFields.length; i<len; i++) {
f.elements[myFields].value = myValues;
}
}
</script>
<form action="">
<input name="Id" type="text" size="20">Id<br>
<input name="callername" type="text" size="20">callername<br>
<input name="address" type="text" size="20">address<br>
<input name="phone" type="text" size="20">phone<br>
<input name="phoneb" type="text" size="20">phoneb<br>
<input name="email" type="text" size="20">email<br>
<input name="sqft" type="text" size="20">sqft<br>
<input name="source" type="text" size="20">source<br>
<input name="action" type="text" size="20">action<br>
<input name="status" type="text" size="20">status<br>
<input type="button" value="Add values" onclick="
var theValues = ['anId','aCallername','anAddress',
'aPhone','aPhoneB','anEmail','aSqft',
'theSource','theAction','theStatus'];
addValues(this.form,theValues);
"><br>
<input type="reset">
</form>