Alternative for DOM Manipulation in client script

kavitha_cr
Mega Guru

Hi All,

I am using the below code in a Onsubmit catalog client script to show an alert for attaching a file before submitting the ticket in the portal.

Script:

function onSubmit() {
try { //Works in non-portal ui
var attachments = document.getElementById('header_attachment_list_label'); //Line3
if (attachments.style.visibility == 'hidden' || attachments.style.display == 'none' ) {
alert("Please attach file before submitting.");
return false;
}
} catch(e) { //For Service Portal
var count = getSCAttachmentCount();
if(count <= 0) {
alert("Please attach file before submitting.");
return false;
}
}
}

According to Best Practice, we will not be using DOM manipulation , so I need to replace the code. Can I get the alternative solution for the line 3 in the above script by not breaking the existing functionality.

Thanks in Advance,

Shilpa.

1 ACCEPTED SOLUTION

Hi,

I haven't tried with this

let us know if that works well

var attachments = g_form.getFormElement('header_attachment_list_label');

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

20 REPLIES 20

AnirudhKumar
Mega Sage
Mega Sage

This can be done without a client script.

There's a checkbox called Mandatory Attachment under the Portal settings section on the catalog item configuration form. Set it to true.

 

Long Live ServiceNow!

Hi Anirudh

I have to change the line 3 code by not using the DOM.

Please let me know the replacement of the code in the line3.

Thanks,

Shilpa.

Aman Singh_
Kilo Sage

Hi,

Use the following code:

Credit: https://community.servicenow.com/community?id=community_blog&sys_id=00edd9751bb090d0ada243f6fe4bcba8.

function onSubmit() {
	//Type appropriate comment here, and begin script below

var countRequired = 1;
	if(window == null){
		// portal
		if(this.document.getElementsByClassName('get-attachment').length != countRequired) {
			alert('You must add 1 attachments before submitting this request.');
			return false;
		}
	}
	else{
		// native view
         var length = $j("li.attachment_list_items").find("span").length;
		if(length != countRequired){
			alert('You must add 1 attachments before submitting this request.');
			return false;
		}
	}
}

Please mark reply as Helpful/Correct, if applicable. Thanks!

Aman

Hi Aman,

Thanks for the response. But 

document.getElementsByClassName

is also a DOM method. Please let me know the replacement of the code other than the DOM methods.

Thanks,

Shilpa.