onChange Client script - clear dependent field when user clears IP address field

BiancaK
Tera Expert

Good Day fellow Devs

 

I am performing a field validation on the IP address field and thereafter I am setting the IP address value to another field (machine name field). 

After setting the IP address field value to machine name field, if the user clears the value in the IP address field the machine name field is not cleared. How do I clear it please?

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
 
    var ip = g_form.getValue('ip_address');
 
    var reg = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
 
    if (!reg.test(ip)) {
        alert('Please enter correct IP Address');
        g_form.clearValue('ip_address', '');
    } else {
        var machineName = ip + ".abc.xxxzzz.corp";
        g_form.setValue("machine_name", machineName);
    }
}
 
BiancaK_0-1690068157352.png

 

I have tried using g_form.clearValue(); but it does not work
 
BiancaK_0-1690068243207.png

 

1 ACCEPTED SOLUTION

Sagar Pagar
Tera Patron

Hi @BiancaK,

 

You need to use the clearValue() ot setValue() with null value for machine name variable. You can try this updated scripts.

UI type: All

 

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {

		g_form.clearValue("machine_name");
		return;
	}

	var ip = g_form.getValue('ip_address');

	var reg = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;

	if (!reg.test(ip)) {
		alert('Please enter correct IP Address');
		g_form.clearValue('ip_address');
	} else {
		var machineName = ip + ".abc.xxxzzz.corp";
		g_form.setValue("machine_name", machineName);
	}
}

 


If my response helps to solve your issue. Kindly mark it as helpful & correct. It will be helpful for future readers.
Thanks,
Sagar Pagar

The world works with ServiceNow

View solution in original post

5 REPLIES 5

Samaksh Wani
Giga Sage
Giga Sage

Hello @BiancaK 

 

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }


 
    var ip = g_form.getValue('ip_address');

    if(ip == ""){
     g_form.setReadOnly('machine_name', false);
     g_form.setValue('machine_name', '');
    }
 
    var reg = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
 
    if (!reg.test(ip)) {
        alert('Please enter correct IP Address');
        g_form.clearValue('ip_address', '');
    } else {
        var machineName = ip + ".abc.xxxzzz.corp";
        g_form.setValue("machine_name", machineName);
    }
}

 

 

Use this code 

 

Plz Mark my Solution as Accept and Give me thumbs up, if you find it Helpful.

 

Regards,

Samaksh