We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

How to check if Date field is empty

davilu
Mega Sage

Hi Community,

This is kind of a silly question, but I'm writing a client script that checks to see if a date field is empty.   If it is empty I want it to clear a couple other fields:

var start = g_form.getValue('from');

var end = g_form.getValue('to');  

if(start=='' || null) {

g_form.setValue('year', '');

g_form.setValue('month', '');

g_form.setValue('day', '');

}

Right now, when I delete the date field, the other fields don't clear out.   However, if I delete the date field and press the space bar, the other fields clear out.   What's the syntax to see if a date field is empty or not?

Thanks!

1 ACCEPTED SOLUTION

I believe it's because we are checking newValue === '' in onChange() function and then returning from there, kindly replace this line



if (isLoading || newValue === '') {



to



if (isLoading) {



please try with below script and see if that helps:



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


if (isLoading) {


return;


}


//Type appropriate comment here, and begin script below


if(newValue == ''){


g_form.setValue('year', '');


g_form.setValue('month', '');


g_form.setValue('day', '');


}


}


View solution in original post

10 REPLIES 10

prasad48
Tera Guru

Try



var start = g_form.getValue('from');


if(start)


{


//code here if date has value


}


else



{


////code here if date has no   value


}


andymcdonald
Mega Guru

pretty sure your if statement is bad...should be


if (start == '' || start == null)



that said, I would probably prefer to just replace it with this


if (! start)



--see if it helps


-Andy


Prateek kumar
Giga Sage

Hello David try this:



var start = g_form.getValue('from');


var end = g_form.getValue('to');



if(start=='') {


g_form.clearValue('year');


g_form.clearValue('month');


g_form.clearValue('day');


}



Please mark my response as correct and helpful if it helped solved your question.
-Thanks

hey prateek_kumar, pdhule, andymcdonald, thanks for the help!   I tried all three suggestions, but nothing worked.   Do I need to create separate client scripts to clear fields?