Client Script: check value of fields and get the value of the one that isn't empty

Amy13
Tera Contributor

Need help writing a client script!

I need to:

check the value of 5 different fields

Only 1 field will not be empty

I need to get the value of the field that's not empty


How would I write this? I'm thinking something involving g_form.getValue().

Thank you!

2 REPLIES 2

Marcin20
Mega Guru

Hi Amy,

 

I propose the following approach (this code can be optimized using a function):

 

var not_empty_value = '';

var field1 = g_form.getValue('field1');

if (field1 != '') {

   not_empty_value  = field1;

 } else {

    var field2 = g_form.getValue('field2');

    if (field2 != '')  {

   not_empty_value  = field2;

   }

} else {

    var field3 = g_form.getValue('field3');

    if (field3 != '')  {

   not_empty_value  = field3;

   }

} else {

    var field4 = g_form.getValue('field4');

    if (field4 != '')  {

   not_empty_value  = field4;

   }

} else {

    var field5 = g_form.getValue('field5');

    if (field5 != '')  {

   not_empty_value  = field5;

   }

}

 

 

Best Regards,

Marcin

 

If my answer helped you in any way, please mark this answer as helpful and correct.

 

Kartik Sethi
Tera Guru
Tera Guru

Hi @Amy 

 

There can be 2 approaches using Client Script as provided below:

  1. Multiple onChange
  2. Single onSubmit

If you prefer to go with Option#1, then you need to create as many onChange Client Scripts as your fields to monitor

If you prefer to go with Option#2, then you need to write only 1 onSubmit Client Script with logic to check for any one field populated.

 

You can opt for the below-provided code:

function onSubmit() {
	//Store backend names of the fields to monitor in an array
	var fields = ['f1', 'f2', 'f3', 'f4', 'f5'],
		notEmptyField = '',
		fieldValue = '';
	
	
	for(var i = 0; i < fields.length; i++) {
		fieldValue = g_form.getValue(fields[i]);
		if(fieldValue != '') {
			notEmptyField = fieldValue;
			
			alert('Field: ' + fields[i] + ' has value: ' + fieldValue);
			break;
		}
	}
}

 


Please mark my answer as correct if this solves your issues!

If it helped you in any way then please mark helpful!

 

Thanks and regards,

Kartik