Skip to main content
Inspiring
February 12, 2021
Answered

Help Simplifying Javascript for a repetitive code! - Please

  • February 12, 2021
  • 1 reply
  • 657 views

I have made a form with the purpose of having multiple dropdowns for inserting an 'ID number' which would then populate the following text fields: 'description,' 'quantity,' and a 'unit.' 

This form is working perfectly as intended but I was wondering if there was a better way to code it.

 

There is a very repetitive code which is needed for assigning the dropdowns to the corresponding fields:

function SetFieldValues1(cID1) {
    this.getField("Desc1").value = DeptData[cID1].description;
    this.getField("Quan1").value = DeptData[cID1].quantity;
    this.getField("Unit1").value = DeptData[cID1].unit;
}
function SetFieldValues2(cID2) {
    this.getField("Desc2").value = DeptData[cID2].description;
    this.getField("Quan2").value = DeptData[cID2].quantity;
    this.getField("Unit2").value = DeptData[cID2].unit;

,Etc....

 

and this is linked to the dropdowns as such:

(ID1)Custom Keystroke Script:

if( event.willCommit )
{
   if(event.value == " ")
     this.resetForm(["Desc1","Quan1","Unit1"]);
   else
     SetFieldValues1(event.value);
}

(ID2)Custom Keystroke Script:

if( event.willCommit )
{
   if(event.value == " ")
     this.resetForm(["Desc2","Quan2","Unit2"]);
   else
     SetFieldValues2(event.value);
}

,Etc....

 

Is there a simpler way to do this? 

Any help would be amazing

Thank you all in advance!

-Flynn Hammonds

This topic has been closed for replies.
Correct answer try67

Try this:

 

// Generic code
function SetFieldValues(cID, idx) {
    this.getField("Desc"+idx).value = DeptData[cID].description;
    this.getField("Quan"+idx).value = DeptData[cID].quantity;
    this.getField("Unit"+idx).value = DeptData[cID].unit;
}

// IDx custom Keystroke script
var idNumber = event.target.name.replace("ID", "");
if( event.willCommit )
{
   if(event.value == " ")
     this.resetForm(["Desc"+idNumber,"Quan"+idNumber,"Unit"+idNumber]);
   else
     SetFieldValues(event.value, idNumber);
}

1 reply

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
February 12, 2021

Try this:

 

// Generic code
function SetFieldValues(cID, idx) {
    this.getField("Desc"+idx).value = DeptData[cID].description;
    this.getField("Quan"+idx).value = DeptData[cID].quantity;
    this.getField("Unit"+idx).value = DeptData[cID].unit;
}

// IDx custom Keystroke script
var idNumber = event.target.name.replace("ID", "");
if( event.willCommit )
{
   if(event.value == " ")
     this.resetForm(["Desc"+idNumber,"Quan"+idNumber,"Unit"+idNumber]);
   else
     SetFieldValues(event.value, idNumber);
}
Flynn0101Author
Inspiring
February 12, 2021

@try67 

You are my hero!

Thank you so much! 

❤️ ❤️