How to set CRM javascript value to null? - javascript

I have the following JavaScript code in a Dynmaics library, however the code does not set the value to null in the else condition any ideas to why? I believe my code is correct.
Please advise. My null setting isnt working I also tried removeAttribute();it does not work
function validateSortCode(executionContext) {
var formContext = executionContext.getFormContext();
var sortcode = formContext.getAttribute("sortcodee").getValue();
var errorId = "error";
if(sortcode != "")
{
var sortcoderegex = /^(\d){2}-(\d){2}-(\d){2}$/;
if(sortcoderegex.test(sortcode) == false)
{
formContext.ui.setFormNotification("Please ensure correct format of Sort Code i.e. 12-34-56", "ERROR", errorId);
}
else
{
formContext.getAttribute("sortcodee").setValue(null);
//formContext.getAttribute("sortcodee").removeAttribute("sortcodee");
}
}
}

You need to set the value after your notification of the error to null.
Try this.
function validateSortCode(executionContext) {
var formContext = executionContext.getFormContext();
var sortcode = formContext.getAttribute("sortcodee").getValue();
var errorId = "error";
if(sortcode != "")
{
var sortcoderegex = /^(\d){2}-(\d){2}-(\d){2}$/;
if(sortcoderegex.test(sortcode) == false)
{
formContext.ui.setFormNotification("Please ensure correct format of Sort Code i.e. 12-34-56", "ERROR", errorId);
formContext.getAttribute("sortcodee").setValue("");
}
else
{
formContext.ui.clearFormNotification(errorId);
}
}
}
The above should do the trick

Related

Call functions from sources directly in Chrome console?

For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

Can't seem to move segment into repeating field

I have a piece of code that I'm trying to get to work on an interface. Basically we take some fields and drop into other segments. The problem seems to be that it leaves the data where it is instead of moving it to the indexed PID segment. Also the CP variable is returning 'undefined' for some reason.
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
msg['PID']['PID.13'][i] = "";
}
msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;
Sample HL7 msg I am using before transforms (from our test system, NOT live data)
It should resemble this instead:
|9999999999^^^test#test.com~99999999999~~~|
Any ideas/pointers on why it's not moving?
You are missing a toString() when you set the variables. A typical Mirth thing, because you get the E4X object back in the variable instead of the value you expected.
In addition to this, you should check the variables for undefined values before setting them on the new structure because otherwise you end up with "undefined" in the fields.
This is a working solution:
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
msg['PID']['PID.13'][i] = "";
}
if(homeNum != null) msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
if(netNum != null) msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
if(cpNum != null) msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;

Calling the filter method on a JQuery object is not working when done inside of a function

My knowledge of jQuery and more specifically javascript has always been very limited and I am working hard to get better.
With that in mind I am trying to create some sort of "extensible validation framework" in that I can create an object with a validation function and its error message, push it into an array and then call all those methods and report the messages from the ones that fail.
So first I did something very simple just to see that the basic validation worked which was this:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var isDateBooked = list.filter(function () {
return (this.innerHTML == selectedTourDate) ;
}).length !== 0;
if (isDateBooked) {
alert("Date invalid");
return;
}
This works fine.
Then I created my "framework" which is this:
function Validator(fn, errorMessage) {
this.validationFunction = fn;
this.errorMessage = errorMessage;
};
var validationRunner = {
validators: [],
errorMessages: [],
validationResult: true,
addValidation: function (validator) {
validationRunner.validators.push(validator);
},
validate: function () {
for (var validator = 0; validator < validationRunner.validators.length; validator++) {
if (validationRunner.validators[validator] instanceof Validator) {
var result = validationRunner.validators[validator].validationFunction();
validationResult = validationRunner.validationResult && result;
if (!result)
validationRunner.errorMessages.push(validationRunner.validators[validator].errorMessage);
}
}
},
getErrorMessage: function () {
var message = "<ul>";
for (var errorMessage = 0; errorMessage > validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + errorMessage + "</li>";
}
message += "</ul>";
return message;
}
}
And then modified the first block of code as follows:
var selectedTourDate = $("#tourDate").val();
var list = $("#bookedTourDate *");
var tmp = new Validator(function () {
return list.filter(function () {
return (this.innerHTML == selectedTourDate);
}).length !== 0;
}, "Date already booked");
validationRunner.addValidation(tmp);
validationRunner.validate();
var msg = validationRunner.getErrorMessage();
This does not work at all.
It seems that the problem is that in this statement:
return (this.innerHTML == selectedTourDate);
The "this" is the Validator object instead of the html element from the list which confuses me since as its inside the function of the "filter" method it should be.
Is there a way to correct this so I can accomplish what I am trying to do here?
this does have the correct value but there are some mistakes in the getErrorMessage function.
To check the value of this don't rely on a debugger's "watch variable" function but do a console.log which will give you the value at a specific point of the code execution.
My changes:
for (var errorMessage = 0; errorMessage < validationRunner.errorMessages.length; errorMessage++) {
message += "<li>" + validationRunner.errorMessages[errorMessage] + "</li>";
}
The errorMessage variable is only a index and not the actual error message. Also you used a "bigger than" instead of a "smaller than" sign.
Here's a fiddle
That is very odd, as this should be the current DOM element per jquery api.
The function should take an index as a parameter, though. So what about trying
return list.filter(function (i) {
return (list.get(i).innerHTML == selectedTourDate);
}).length !== 0;

Loading form input fields into a javascript array and then validating

I seem to be really stuck on something. I have a function to check if all the form input fields are equal to null or "" which is all fine but wanted to see if there is another way of doing it by loading all the fields into a javascript array and then doing a for loop along with an if statement to check if any of the fields are empty, unfortunately I can't seem to get this to work and wondering if I've simply just missed something some where. Here is my code:
function checkempty()
{
fname = document.getElementById("firstname").value;
lname = document.getElementById("lastname").value;
fage = document.getElementById("age").value;
addressl1 = document.getElementById("addressline1").value;
addressl2 = document.getElementById("addressline2").value;
ftown = document.getElementById("town").value;
fcounty = document.getElementById("county").value;
fpcode1 = document.getElementById("pcode1").value;
fpcode2 = document.getElementById("pcode2").value;
ftelephone = document.getElementById("telephone").value;
fcomment = document.getElementById("comment").value;
var myArray = [];
myArray[0] = fname;
myArray[1] = lname;
myArray[2] = fage;
myArray[3] = addressl1;
myArray[4] = addressl2;
myArray[5] = ftown;
myArray[6] = fcounty;
myArray[7] = fpcode1;
myArray[8] = fpcode2;
myArray[9] = ftelephone;
myArray[10] = fcomment;
for(i=0;i<myArray.length;i++)
{
if(!myArray[0])
{
return true;
}
}
return false;
}
I then use another function:
function checkform()
{
if(checkempty)
{
display_errormessage("One or more fields empty!");
}
else
{
alert("Thanks for you input!");
}
}
The display_errormessage() function is just one that puts an error message into a div at the top of the form to display an error message if the form is incomplete.
Can anyone see where i've gone wrong?
Thanks in advance for any help!
Dave.
First, function checkform is not called. The if (checkform) should be if (checkform()) or you will test only test the availability of the function, not the result.
Then the if (!myArray[0]) should be if (!myArray[i]) to not only test the firstname
Or better, if (myArray[i].length==0) to be sure to explicitly test for empty string and not just doing an implicit boolean conversion (javascript evaluate 0=="" as true)
if(!myArray[0]) should be if(!myArray[i]), but a larger point is you're only validating that the value isn't falsey (null, '', 0, false, etc.), not that it's appropriate for the task.
Guess you won't need this function as you've already fixed yours, but I'll leave it here as it may be helpful in the future. JSFiddle
function checkform()
{
arr1 = document.getElementsByTagName('input');
arr1 = Array.prototype.slice.call(arr1);
arr2 = document.getElementsByTagName('textarea');
arr2 = Array.prototype.slice.call(arr2);
arrs = arr1.concat(arr2);
for(i=0;i<arrs.length;i++)
{
if (arrs[i].type == "text" || arrs[i].type == "textarea")
{
if (arrs[i].value == '')
{
alert("Fill all fields before submitting!");
return false;
}
}
}
alert("Thanks for your input!");
return true;
}
According that your input fields are in the form named form:
var allTrue = [].every.call( document.forms.form.elements, function( el ) {
return !!el.value;
} );
if ( allTrue ) {
alert( "Thanks for your input!" );
}
else {
alert( "Some fields are missing!" );
}

Categories

Resources