ServiceNow show button if condition is true - javascript

I am trying to build a Client Script in ServiceNow - Geneva (function onChange), that does the following:
-> If the user writes something in an empty field a button should appear after change;
This is my code now, it doesn't work -> gives me an X on the form :):
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
//Define the variable and the name of the button
if (g_form.getValue('work_around') != ''){
var items = $$('BUTTON').each(function(item){
if(item.innerHTML.indexOf('Publish Known Error')=== -1){
item.show();
}
});
}
}

Instead of a Client Script, I would recommend using an onChange(<your field>) UI Policy. This can be accomplished by setting a Condition of your field not being NULL or some other value check.
Your UI Policy can then use the .append function to bind your button to an element of your choice.

Related

Marketo Hidden Field update

How should I update the value of a hidden field of Marketo?
What I have tried
form.setValues({"Results_PDF_URL__c":"assignedCampaignID"});
form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
Both of the above options don't work.
So I checked the id, if I am using the right id, when I tried to get the id it retured blank (nothing) for hidden marketo fields.
While I can get the id for input text Marketo fileds (like FirstName, Comapany..) - I am not able to get the id of any hidden Marketo fields.
Any idea what I should set to get this to work?
Either of those, as long as they're used in the right scope, should work. The form object is not global.
MktoForms2.whenReady( function (form) {
form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
});
You'll first want to make sure the MktoForms2 API is available so you don't get an error.
if( typeof MktoForms2 != "undefined" ) {
MktoForms2.whenReady( function (form) {
form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
});
}
In Marketo, you can get the field names under Admin > Field Management > Export Field Names. (Requires Marketo admin access.) This will download a CSV of all the field names. You will want to use the field names shown in the REST API column.
For a quick check, I usually just add the fields I want to a form and inspect them to get the correct field IDs.
Also, you can use .addHiddenFields() instead of .vals() to ensure that the fields are a) on the form b) as hidden fields and c) have the correct values that you want to pass into Marketo. If the fields already exist, this function will detect the fields and only set the values. Very handy.
if( typeof MktoForms2 != "undefined" ) {
MktoForms2.whenReady( function (form) {
form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
});
}
Finally, you may want to add a brief delay to ensure that the Marketo forms library has ample time to load and that the form will be available on the page when you look for it. It's unlikely that someone will submit the form in the first two seconds on the page, so it is probably okay to delay for two seconds before adding the field/value to the form.
setTimeout( function(){
if( typeof MktoForms2 != "undefined" ) {
MktoForms2.whenReady( function (form) {
form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
});
}
}, 2000 ); // two-second delay
Resources:
Marketo forms API Reference
Marketo forms API Examples

Business required lookup set by javascript error

I´m working on a javascript event in dynamics crm 2013.
I have an option set (let´s call it fieldA). When it changes, I want to set the value of a lookup (let´s call it fieldB). This lookup is mandatory (or business required as CRM calls it).
Here is my code:
function fieldAOnChange() {
/* computation of field B value: entityId, name, entityType */
var lookupField = Xrm.Page.getAttribute(fieldBId);
if (!isUndefined(lookupField)) {
if (entityId != null && name != null && entityType != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = entityId;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
lookupField.setValue(lookupValue);
} else {
lookupField.setValue(null);
}
lookupField.fireOnChange();
}
}
This code works almost fine. The lookup is correctly filled, however the icon "this is a mandatory field and it´s not filled" appears next to the field. This is what I´m trying to fix !
If I click on the field to get the focus and then elsewhere to lose it, the icon disappear. If I change again the value in the option set and the fieldB is updated again, the icon disappear also.
I have tried stupid things like setting the focus on and off or launching the fireOnChange event twice without results.
Am I doing something wrong ?

Detecting if I have already alerted a message

I have a page that loads some data into a model and one of the properties of the model has an errormessage. I have a js file that checks if the errormessage is there; if so, it displays an alert with the message itself like this:
function CheckErrMsg(model) {
if (model.CallStatusStatus() == -111) {
alert(model.CallStatusErrorMessage());
}
}
Whenever I'm done doing whatever with the object I have loaded it automatically loads another one and if this checks out for the new model then it will display the alert again.
I want the alert to be displayed only for the first model loaded, so I guess I need to know if there is a way to check if that alert was already displayed and if so don't display it again.
You can add an IsAlertShown field to the model then check it before alerting:
model.IsAlertShown = ko.observable(false);
if (!model.IsAlertShown() && model.CallStatusStatus() == -111) {
model.IsAlertShown(true);
alert(model.CallStatusErrorMessage());
}
Yet, personally I don't like to 'pollute' my View-Model (which is usually about to be sent back to the server) with stuff that are purely UI-related. So I would expose the flag as part of the function itself:
if (!CheckErrMsg.IsAlertShown && model.CallStatusStatus() == -111) {
CheckErrMsg.IsAlertShown = true;
alert(model.CallStatusErrorMessage());
}
(Since in JavaScript functions are also objects, you can set properties on functions as well)
Just set a flag:
messageDisplayed=0;
function CheckErrMsg(model) {
if (model.CallStatusStatus() == -111 && messageDisplayed==0) {
alert(model.CallStatusErrorMessage());
messageDisplayed=1;
}
}
That'll do the trick.

Javascript Object Ready?

I have a function that uses AJAX to get a list of items from a php script and can pass a filter. The user can set the filter by selecting from a drop down box on the page.
The problem i'm having is I am calling the function during page load to fill the form with default data and the function is just quitting silently when I try to read the filter text from the drop down box. It works fine after page load, but not during. However the function works fine if I put an alert("test") before it tries to read from the drop down so i'm assuming the drop down just hasnt finished loading properly when the function is called. How can I test to see if its safe to read so I can provide my own default value if it isnt safe?
Code Snippit:
var ProdCat = document.getElementById("prod_cat2");
var Filter = "All Products";
Filter = ProdCat.options[ProdCat.selectedIndex].text;
alert("test");
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();
So the above code is in a function called onLoad and the alert doesnt trigger at all. But if I comment out the Filter = ProdCat.(etc) line then the alert DOES trigger. Alert ALWAYS triggers even with that line AFTER page load. Looking for a solution to keep the one function both during load and after, thanks!
It sounds like the script is above the markup for the ProdCat select box in your HTML file. If so, the simplest thing is to simply move the script tag containing it down so that it's underneath the markup for the select box. The select box won't exist until its markup is parsed, but it will exists immediately once it is.
How can I test to see if its safe to read so I can provide my own default value if it isnt safe?
If you don't want to relocate the script (or you run into this in other situations where that doesn't make sense), you can test whether you got the element:
if (ProdCat) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
If you like, you can even have it retry:
var ProdCat;
var Filter = "All Products";
function startAjax() {
ProdCat = document.getElementById("prod_cat2");
if (ProdCat) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();
else {
setTimeout(startAjax, 100); // 1/10th of a second later, try again
}
}
startAjax();
Update: In a comment, you said:
The error is: ProdCat.options[ProdCat.selectedIndex] is undefined
Okay, so you have the element, but there's nothing selected (yet). So the test would be:
if (ProdCat && // We have the select
ProdCat.selectedIndex >= 0 && // and it has a selected value
ProdCat.options[ProdCat.selectedIndex] // (Paranoia) and that option exists
) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
Check if the element could be found. If not, the default filter 'All Products' is used.
var ProdCat = document.getElementById("prod_cat2");
var Filter = "All Products";
if (ProdCat)
{
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
alert("test");
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();

Form - update "reset" button to new data

I'm using mootools in 1 of my projects. I'm working on easy to be customised menu based on sortables.
So here's the issue - I've got the form which contains menu node informations. Form is updated with JS whenever user chooses different node (form is populated with new data). Problem is that "reset" button obviously "remembers" the initial data, so whenever user clicks it, it loads initial data form.
Is there anyway to update the "default" form status, whenever i load new data? (ofc i could write piece of code which do whatever i need, but if there is some simplier solution which allows default "reset" button to work with new data would be much less work to use it :))
Thanks in advance for help
i cant think of anything else except getting a new source through ajax with data prepopulated and replace the innerhtml hence replacing the form itself.
you can use something like toQueryString to serialize the form and then reverse it based upon the mootools-more's String.parseQueryString():
(function() {
Element.implement({
saveFormState: function() {
if (this.get('tag') !== 'form')
return;
this.store("defaults", this.toQueryString());
},
restoreFormState: function() {
if (this.get('tag') !== 'form')
return;
var vals = this.retrieve("defaults");
if (!vals.length)
return;
var self = this;
Object.each(vals.parseQueryString(vals), function(value, key) {
var el = self.getElement("[name=" + key + "]");
el && el.set('value', value);
});
}
});
})();
var f = document.id('f');
// save default
f.saveFormState();
document.getElement("button").addEvent("click", f.restoreFormState.bind(f));
this ough to cover most cases and you can always save a new defaults state. need to test it somewhat with radios and suchlike, though.
here's a basic fiddle with a save/restore: http://jsfiddle.net/UWTUJ/1/
relevant docs: http://mootools.net/docs/more/Types/String.QueryString (more) and http://mootools.net/docs/core/Element/Element#Element:toQueryString (core)
implied reliance on name attributes on all form elements you want to save/restore.
I have previously created more complex save/restore states that even return field CSS class names, validation messages, etc.

Categories

Resources