Javascript we had for Unified interface of Dynamics 365 to format phone numbers was working perfectly until the latest update, now it only works in custom interface and has stopped working in UI, anybody has any idea how this can be fixed?
var XXX = window.XXX || {};
(function() {
// Code to run in the form OnLoad event
this.formOnLoad = function(executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function() {
formContext.ui.clearFormNotification(myUniqueId);
}, 5000);
}
// Code to run in the attribute OnChange event
this.mobilePhoneFormatting = function(executionContext) {
var formContext = executionContext.getFormContext();
var mobilePhone = formContext.getAttribute("mobilephone").getValue();
var formatPhone = "";
try {
if (mobilePhone != null) {
var phoneNumbers = mobilePhone.replace(/\D/g, '');
if (phoneNumbers.length == 10) { //10 digit case. Output adds +1 and proper format
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10));
} else if (phoneNumbers.length == 11) { //11 digit case. Output proper format
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11));
} else if (phoneNumbers.length == 14) { //14 digit case. Without Country code and with extension
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10) + " x" + phoneNumbers.substring(10, 14));
} else if (phoneNumbers.length == 15) { //15 digit case. With Country code and extension
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11) + " x" + phoneNumbers.substring(11, 15));
} else if (phoneNumbers.length == 4) { //4 digit case. Extension Only
formatPhone = ("x" + phoneNumbers.substring(0, 4));
} else {
formatPhone = mobilePhone;
}
formContext.getAttribute("mobilephone").setValue(formatPhone);
formContext.data.entity.save();
}
} catch (err) {
txt = "There was an error formatting the Phone Number.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
I'm trying to improve the following script by adding some randomness to it. Because right now it only bets on the "double_your_btc_bet_hi_button" id.
My idea is to generate a random number and make the bet based the its outcome. But I'm not sure how I supose to do that.
The id of the other bet buttom is "double_your_btc_bet_lo_button".
var minstake = 0.00000001; // valor base
var autorounds = 100; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresults, 123);
return;}
function checkresults() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresults, 246);
return;
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong'); return; }
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
return;
}
setTimeout(playnow, 111);
return;
}playnow()
I've tried to use Math.random but now it only bets lo and only plays once.
var minstake = 0.00000001; // valor base
var autorounds = 99999; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function getRandomNumber() {Math.floor(Math.random() * 2) + 1;
};
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
if (getRandomNumber!==1) {
document.getElementById('double_your_btc_bet_lo_button').click();
setTimeout(checkresultslo, 123);
return;
function checkresultslo() {
if (document.getElementById('double_your_btc_bet_lo_button').disabled === true) {
setTimeout(checkresultslo, 246);
return;}}}
if (getRandomNumber!==2) {
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresultshi, 123);
return;
function checkresultshi() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresultshi, 246);
return;}}}
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong');}
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
}
setTimeout(playnow, 111);
playnow()
I am new to Javascript. Below is simple program where I am trying to display elements from array that I have created. It does not work. Can anybody please let me know what I am doing wrong?
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Javascript Excercises - Functions</title>
<script>
function findPrimeFactors(){
var primefacts = [];
var primefacs;
var unum = prompt("Please enter a positive number");
var i = 2;
var num = parseInt(unum);
if (num > 0) {
while (num >= i){
if (num % i == 0){
primefacts.push(i);
num = num / i;
console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length-1]);
}
else {
i += 1;
}
};
if (primefacts.length = 0) {
document.write("No prime factors other than 1 for this number.");
}
else {
primefacs = primefacts.join();
console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]);
document.write("The prime factor for " + unum + " are : " + primefacs);
}
}
}
</script>
</head>
<body>
<button onclick="findPrimeFactors()">Click to proceed</button>
</body>
replace:-
if (primefacts.length = 0) {
with
if (primefacts.length == 0) {
you are setting the length to 0 instead of comparing.
function findPrimeFactors() {
var primefacts = [];
var primefacs;
var unum = prompt("Please enter a positive number");
var i = 2;
var num = parseInt(unum);
if (num > 0) {
while (num >= i) {
if (num % i == 0) {
primefacts.push(i);
num = num / i;
console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length - 1]);
} else {
i += 1;
}
};
if (primefacts.length == 0) {
document.write("No prime factors other than 1 for this number.");
} else {
primefacs = primefacts.join();
console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]);
document.write("The prime factor for " + unum + " are : " + primefacs);
}
}
}
<button onclick="findPrimeFactors()">Click to proceed</button>
I know this issue has been reported quite some number of times but I am unable to resolve my problem. I am using Javascript AJAX (no jquery) to post some data from html textarea (formatted with CKEditor) to ASP.NET aspx page.
If I post small data, I get the response from aspx page but if I increase the content to 15-20 lines, I get Network Error 404. Here is the screenshot of Firebug Console Error:
Request Headers (From Firebug Net Panel):
And the output is blank so:
The behavior is same on localhost and live website.
Javascript Code:
//function that reads a form and create list of parameters
function submitajaxform(formid, btnid, wid, rid, url, fsuccess, ferror) {
var elem = document.getElementById(formid).elements;
var params = "";
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
//check if valid value exists
if (elem[i].options[elem[i].selectedIndex].value != '') {
params += elem[i].id + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) + "&";
}
} else if (elem[i].type == "checkbox" || elem[i].type == "radio") {
params += elem[i].id + "=" + encodeURIComponent(elem[i].checked) + "&";
} else if (elem[i].type == 'textarea' && elem[i].className == 'ckeditor') {
params += elem[i].id + '=' + window.escape(CKEDITOR.instances[elem[i].id].getData()) + '&';
}
//element none of select, checkbox & radio
else {
params += elem[i].id + "=" + encodeURIComponent(elem[i].value) + "&";
}
}
ajaxmethod = "POST";
globalajax(btnid, wid, params, url, rid, fsuccess, ferror);
}
//function that creates ajax request and sends it
function globalajax(btn, wid, prm, url, rid, fsuccess, ferror) {
//if already running, reschedule to run after 1 second
if (ajaxfinish == 1) {
setTimeout("globalajax('" + btn + "','" + wid + "','" + prm + "','" + url + "','" + rid + "','" + fsuccess + "','" + ferror & "')", 500);
return;
}
//very important to put this here:
ajaxfinish = 0;
//================================
//disable button if supplied
if (btn != '' && document.getElementById(btn) != null) {
document.getElementById(btn).disabled = true;
}
//shows wait msg if container supplied
if (wid != '' && document.getElementById(wid) != null) {
document.getElementById(wid).innerHTML = "<img src='/images/loading.gif' class='imginline' alt='Please Wait...' />"
}
//shows wait box on result container
if (rid != '' && document.getElementById(rid) != null) {
document.getElementById(rid).innerHTML = "<img src='/images/loading.gif' class='imginline' alt='Please Wait...' />";
}
//dont run if ajax is not free
if (ajaxrequest.readyState != 0 && ajaxrequest.readyState != 4) {
setTimeout("globalajax('" + btn + "','" + wid + "','" + prm + "','" + url + "','" + rid + "'" + fsuccess + "','" + ferror & "')", 500);
return;
}
//very important to put this here:
ajaxfinish = 1;
//===============================
var curts = new Date().getTime();
prm += "&curts=" + curts;
ajaxwaiting = 0;
if (ajaxmethod == "POST") {
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.open(ajaxmethod, url + "?" + prm, true);
}
ajaxrequest.onreadystatechange = function () {
//check if request complete
if (ajaxrequest.readyState == 4 && ajaxrequest.status == 200) {
var ajaxresponse = ajaxrequest.responseText;
//enable button
if (btn != '') { document.getElementById(btn).disabled = false; }
//if response is to reload page (check if any message is to be displayed);
if (ajaxresponse.substr(0, 6) == 'RELOAD') { window.location.reload(); return; }
//if response is to redierct page
if (ajaxresponse.substr(0, 8) == 'REDIRECT') { var desturl = ajaxresponse.substr(9, 100); window.location = desturl; return; }
//end wait in wid
if (document.getElementById(wid) != null) { document.getElementById(wid).innerHTML = ''; }
//end wait in rid
if (document.getElementById(rid) != null) { document.getElementById(rid).innerHTML = ''; }
//if error or message is to be displayed, it would contain 'ER;'
if (ajaxresponse.substr(0, 2) == "ER") {
if (document.getElementById(wid) != null) { document.getElementById(wid).innerHTML = ajaxresponse.substr(3, (ajaxresponse.length - 1)); };
}
else {
//write output (if not preceded by 'ER;')
if (document.getElementById(rid) != null) { document.getElementById(rid).innerHTML = ajaxresponse; }
}
//if success function is defined, run it
if (fsuccess != '') { setTimeout(fsuccess, 100); }
ajaxfinish = 0;
ajaxwaiting = 0;
return;
}
if (ajaxrequest.readyState == 4 && ajaxrequest.status != 200) {
//enable button
if (btn != '') { document.getElementById(btn).disabled = false; }
//write error in wait
if (wid != '') { document.getElementById(wid).innerHTML = "<img src='/images/error.gif' width='20' height='20' class='imginline' alt='Error' />An error has occurred. Please try again."; }
//nullify result container
if (rid != '') { document.getElementById(rid).innerHTML = ""; }
//if error function is defined, run it
if (ferror != '') { setTimeout(ferror, 100); }
ajaxfinish = 0;
ajaxwaiting = 0;
//log it
//---
}
}
ajaxrequest.send();
setTimeout("globalajaxabort('" + btn + "','" + wid + "')", 1000);}
There are some global variables that are used here, I have not included their declarations.
In web.config set maxAllowedContentLength .
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="104857600"/>
</requestFiltering>
</security>
and be sure :
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647">
</jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
I have made some modification on your ajax request .. changed it get to post let me know its work for you or not.
//function that reads a form and create list of parameters
function submitajaxform(formid, btnid, wid, rid, url, fsuccess, ferror) {
var elem = document.getElementById(formid).elements;
var params = new Array();
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
//check if valid value exists
if (elem[i].options[elem[i].selectedIndex].value != '') {
params.push([elem[i].id, encodeURIComponent(elem[i].options[elem[i].selectedIndex].value)]);
}
} else if (elem[i].type == "checkbox" || elem[i].type == "radio") {
params.push([elem[i].id, encodeURIComponent(elem[i].checked)]);
} else if (elem[i].type == 'textarea' && elem[i].className == 'ckeditor') {
params.push([elem[i].id, window.escape(CKEDITOR.instances[elem[i].id].getData())]);
}
//element none of select, checkbox & radio
else {
params.push([elem[i].id, encodeURIComponent(elem[i].value)]);
}
}
ajaxmethod = "POST";
globalajax(btnid, wid, params, url, rid, fsuccess, ferror);
}
//function that creates ajax request and sends it
function globalajax(btn, wid, prm, url, rid, fsuccess, ferror) {
//if already running, reschedule to run after 1 second
if (ajaxfinish == 1) {
setTimeout("globalajax('" + btn + "','" + wid + "','" + JSON.stringify(prm) + "','" + url + "','" + rid + "','" + fsuccess + "','" + ferror & "')", 500);
return;
}
//very important to put this here:
ajaxfinish = 0;
//================================
//disable button if supplied
if (btn != '' && document.getElementById(btn) != null) {
document.getElementById(btn).disabled = true;
}
//shows wait msg if container supplied
if (wid != '' && document.getElementById(wid) != null) {
document.getElementById(wid).innerHTML = "<img src='/images/loading.gif' class='imginline' alt='Please Wait...' />"
}
//shows wait box on result container
if (rid != '' && document.getElementById(rid) != null) {
document.getElementById(rid).innerHTML = "<img src='/images/loading.gif' class='imginline' alt='Please Wait...' />";
}
//dont run if ajax is not free
if (ajaxrequest.readyState != 0 && ajaxrequest.readyState != 4) {
setTimeout("globalajax('" + btn + "','" + wid + "','" + JSON.stringify(prm) + "','" + url + "','" + rid + "'" + fsuccess + "','" + ferror & "')", 500);
return;
}
//very important to put this here:
ajaxfinish = 1;
//===============================
var curts = new Date().getTime();
prm.push(["curts", curts]);
ajaxwaiting = 0;
if (ajaxmethod == "POST") {
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.open(ajaxmethod, url, true);
ajaxrequest.send({data:prm} );
}
ajaxrequest.onreadystatechange = function () {
//check if request complete
if (ajaxrequest.readyState == 4 && ajaxrequest.status == 200) {
var ajaxresponse = ajaxrequest.responseText;
//enable button
if (btn != '') { document.getElementById(btn).disabled = false; }
//if response is to reload page (check if any message is to be displayed);
if (ajaxresponse.substr(0, 6) == 'RELOAD') { window.location.reload(); return; }
//if response is to redierct page
if (ajaxresponse.substr(0, 8) == 'REDIRECT') { var desturl = ajaxresponse.substr(9, 100); window.location = desturl; return; }
//end wait in wid
if (document.getElementById(wid) != null) { document.getElementById(wid).innerHTML = ''; }
//end wait in rid
if (document.getElementById(rid) != null) { document.getElementById(rid).innerHTML = ''; }
//if error or message is to be displayed, it would contain 'ER;'
if (ajaxresponse.substr(0, 2) == "ER") {
if (document.getElementById(wid) != null) { document.getElementById(wid).innerHTML = ajaxresponse.substr(3, (ajaxresponse.length - 1)); };
}
else {
//write output (if not preceded by 'ER;')
if (document.getElementById(rid) != null) { document.getElementById(rid).innerHTML = ajaxresponse; }
}
//if success function is defined, run it
if (fsuccess != '') { setTimeout(fsuccess, 100); }
ajaxfinish = 0;
ajaxwaiting = 0;
return;
}
if (ajaxrequest.readyState == 4 && ajaxrequest.status != 200) {
//enable button
if (btn != '') { document.getElementById(btn).disabled = false; }
//write error in wait
if (wid != '') { document.getElementById(wid).innerHTML = "<img src='/images/error.gif' width='20' height='20' class='imginline' alt='Error' />An error has occurred. Please try again."; }
//nullify result container
if (rid != '') { document.getElementById(rid).innerHTML = ""; }
//if error function is defined, run it
if (ferror != '') { setTimeout(ferror, 100); }
ajaxfinish = 0;
ajaxwaiting = 0;
//log it
//---
}
}
ajaxrequest.send();
setTimeout("globalajaxabort('" + btn + "','" + wid + "')", 1000);
}
I am coding a quiz and need to have it display a certain answer depending on the score.
I had this working when I just had the score being displayed, but now that I have added in the if else, it has stopped working and I am getting an unterminated string constant
$total_score = $first_question + $second_question + $third_question + $fourth_question + $fifth_question + $sixth_question + $seventh_question + $eighth_question + $ninth_question + $tenth_question + $eleventh_question + $twelfth_question + $thirteenth_question + $fourteenth_question + $fifthteenth_question + $sixteenth_question ;
});
$("#btn").click(function() {
$('#reveal').html("<h3><strong>Total score</strong> " + $total_score +"</h3>");
if ($total_score >= 13) {
$('#answer').html("<h3><strong>13-16: Answer</strong></h3>");
} else if ($total_score >=9 && $total_score <= 12) {
$('#answer').html("<h3><strong>9-12: answer</strong></h3>");
} else if ($total_score >=5 && $total_score <= 8) {
$('#answer').html("<h3><strong>5-8: answer</strong></h3>");
} else {
$('#answer').html("<h3><strong> everything else</strong></h3>");
}
});
In addition to the line breaks as #Spork noted, you need to remove the extraneous "})" after the $total_score calculation:
$total_score = $first_question + $second_question + $third_question + $fourth_question + $fifth_question + $sixth_question + $seventh_question + $eighth_question + $ninth_question + $tenth_question + $eleventh_question + $twelfth_question + $thirteenth_question + $fourteenth_question + $fifthteenth_question + $sixteenth_question ;
/* must remove the following:
});
*/
$("#btn").click(function() {
$('#reveal').html("<h3><strong>Total score</strong> " + $total_score +"</h3>");
if ($total_score >= 13) {
$('#answer').html("<h3><strong>13-16: Answer </strong></h3>");
} else if ($total_score >=9 && $total_score <= 12) {
$('#answer').html("<h3><strong>9-12: answer </strong></h3>");
} else if ($total_score >=5 && $total_score <= 8) {
$('#answer').html("<h3><strong>5-8: answer </strong></h3>");
} else {
$('#answer').html("<h3><strong> everything else</strong></h3>");
}
});
Javascript treats line ends roughly as semicolons (;), so you cannot have multi-line strings as you have in your script. Remove them, and it'll be okay.