Is there a way to check to see if a field is visible within a script?

galavodasal
Giga Expert

I have this simple onSubmit script to check to see if the user entered at least 12 digits into a field. The problem is, this field isn't always shown on the catalog item. The mac_address field only appears (and becomes mandatory) if another field is set to X.

I was looking in the scripting wiki and saw the g_form.setVisible, but I'm not sure if I can use that in this case.

I tried adding if (g_form.setVisible('mac_address', true)) {   but that just made the entire script fail.

function onSubmit() {

    //Type appropriate comment here, and begin script below

if

  var mac = g_form.getValue('mac_address');  

if (mac.toString().length < 12) { // or whatever number you want  

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

      alert('Please enter the full 12 digit MAC address.');  

}  

   

}

Thanks!

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

You can check to see if the field is mandatory or not, but not whether it is displayed/visisble.



g_form.isMandatory(fieldName) will return true or false.



Since you cannot hide a mandatory field (at least with UI policies) you can tell whether or not the field is visible or not.




GlideForm (g form) - ServiceNow Wiki



There may be a way to do it with g_form.getControl(), but I haven't dug in to the returned HTMLElement to know what you get back.


View solution in original post

7 REPLIES 7

Chuck Tomasi
Tera Patron

You can check to see if the field is mandatory or not, but not whether it is displayed/visisble.



g_form.isMandatory(fieldName) will return true or false.



Since you cannot hide a mandatory field (at least with UI policies) you can tell whether or not the field is visible or not.




GlideForm (g form) - ServiceNow Wiki



There may be a way to do it with g_form.getControl(), but I haven't dug in to the returned HTMLElement to know what you get back.


Perfect, that's a great idea and it looks like it worked.


Actually, one issue, the script works but it still adds the item to the cart. How can I prevent this from happening?



Whoops never mind, just needed the return false; at the end.


If you want to cancel an onSubmit() client script, simply return false if your condition is not met.