Else-if syntax error? - javascript

var to = ['user1', '#user2', 'user3#email.com']
The following codeset should keep 'user1' in the to array, remove the '#' from the start of '#user2', and move 'user3#email.com' to the toEmail array
Right now, else if (toName[j] == '#') { is logging 'syntax error'
var toEmail = [];
var pushToEmail;
for (i=0; i<to.length; i++) {
var pushToEmail = false;
var toName = to[i];
for (j=0; j<toName.length; j++) {
if (toName[0] == '#') {
toName[0] = toName[0].replace(/#/g, ''); // remove '#''
}
console.log('toName[0] = ' + toName[0]);
else if (toName[j] == '#') {
pushToEmail = true;
break;
}
}
if (pushToEmail == true) {
toEmail += to.splice(INDEX, 1)[i];
}
}

You have a syntax error. You can't just throw a console.log in the space between an if and an else. The else has to be attached to an if statement, you've tried to attach that else to a console.log.

Related

How can I stop this from writing a value to all dictionaries? (Javascript)

Intro
So I have stumbled across this problem yesterday, and I've been stumped trying to figure this out myself. I only have this problem with JavaScript.
Problem
I've been creating a programming language with JS since the start of this week, and I was enjoying myself the entire week making it. The problem here is that when I carry dictionaries across functions, it has some problems reading and writing into those dictionaries. When I check the console logs, I see that not just the dictionary in the function was written, but all of the instances of that dictionary were written.
Code
Here is the code to graph.js:
function codeToArray(code) {
let codeArray = {commands:[], vars:{x:{value:0, read_only:true},y:{value:0, read_only:false}}};
let commands = code.split("\n");
for (i = 0; i < commands.length; i++) {
let command = commands[i];
let inputs = command.split(" ");
if (inputs[0].toLowerCase() !== ";") {
// Arithmetics
if (inputs[0].toLowerCase() === "+") { // Addition
codeArray.commands.push({name:"add", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "-") { // Subtraction
codeArray.commands.push({name:"subtract", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "*") { // Multiplication
codeArray.commands.push({name:"multiply", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "/") { // Division
codeArray.commands.push({name:"divide", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// I/O
else if (inputs[0].toLowerCase() === ":") { // Set
codeArray.commands.push({name:"set", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// Conditional Statements
else if (inputs[0].toLowerCase() === "if") { // If Statement
let ifCommand = "";
for (j = 4; j < inputs.length; j++) {
if (j > 4) {
ifCommand += " " + inputs[j];
} else {
ifCommand += inputs[j];
}
}
let ifCommandArray = codeToArray(ifCommand).commands[0];
codeArray.commands.push({name:"if", value1:inputs[1], condition:inputs[2], value2:inputs[3], command:ifCommandArray, syntax_id:2});
}
}
}
return codeArray
}
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
function runCodeArray(commands, variables) {
for (i = 0; i < commands.length; i++) {
let command = commands[i];
if (command.syntax_id === 1) { // Simple Syntax (Variable Value Syntax)
if (command.name === "add") { // Addition
let variable = variables[command.variable];
if (variable === undefined) {
let error_message = `Variable cannot be found (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value += value;
} else if (command.name === "set") { // Set
let variable = variables[command.variable];
if (variable === undefined) {
variables[command.variable] = {value:0, read_only:false};
variable = variables[command.variable];
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value = value;
}
}
}
return {commands:commands, variables:variables, return_message:true};
}
var url_string = ...graph.html?pattern=%3A+a+42%0D%0A%3A+b+%24a%0D%0A%3A+c+%24b%0D%0A // window.location.href;
var url = new URL(url_string);
var pattern = url.searchParams.get("pattern");
let codeArray = codeToArray(pattern);
// console.log(codeArray);
let codeArrayOut = runCodeArray(codeArray.commands, codeArray.vars); // Will return true in return_message if everything is good, and will return a string in return_message if an error occurs.
// console.log(codeArrayOut);
if (codeArrayOut.return_message !== true) {
alert("Error: " + codeArrayOut.return_message);
}
Sorry if the code is too long, boring or messy for you to read. Here is the function that's causing the most problems:
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
Outro
I'm still learning in JavaScript, so I hope that you can solve this problem (because I can't).

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Remove Required Field from QuickCreate in Sugarcrm

I wrote a function to remove accounts name relate field from Contacts QuickCreate but my function works in Firefox perfectly but in chrome its not working... Here is my function
function manageRequired(reqArr, disabledVal)
{
var requiredLabel = '<span class="required">*</span>'; // for firefox
var search_requiredLabel = '<span class="required"'; // searching string for firefox
var form = "";
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i].id=='EditView')
{
form = 'EditView';
break;
}
if(document.forms[i].id=='form_SubpanelQuickCreate_Contacts')
{
form = 'form_SubpanelQuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Contacts')
{
form = 'form_QuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Accounts')
{
form = 'form_QuickCreate_Accounts';
break;
}
}
for(var j = 0; j < reqArr.length; j++)
{
var flag = true;
if (validate[form] != 'undefined')
{
for(var i = 0; i < validate[form].length; i++)
{
if(validate[form][i][0] == reqArr[j].id && validate[form][i][2])
{
if(disabledVal)
{
flag = false;
break;
}
else
{
validate[form][i][2] = false;
}
}
}
}
var labelNode = document.getElementById(reqArr[j].id + '_label');
if(flag & disabledVal)
{
// we require the field now
addToValidate(form, reqArr[j].id, reqArr[j].type, true,reqArr[j].label );
}
if(disabledVal)
{
if(labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1) // for IE replace search string
{
search_requiredLabel = '<SPAN class=required>';
}
if (labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1)
{
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
labelNode.innerHTML = labelNode.innerHTML + requiredLabel;
}
}
else
{
if(labelNode != null)
{
if(labelNode != null && labelNode.innerHTML.indexOf("<SPAN class=required>*</SPAN>") == -1 && labelNode.innerHTML.indexOf('<span class="required">*</span>') == -1 )// for that field which is unrequired
{
}
else if(labelNode != null && labelNode.innerHTML.indexOf(requiredLabel) == -1) // for IE replace span string
{
requiredLabel = "<SPAN class=required>*</SPAN>";
}
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
}
}
}
}
Can anyone please help me out to solve this issue...
To remove a required field from QuickCreate in Sugarcrm you can use this fuction:
removeFromValidate('EditView','eventlist_c');
or remove remove the validtion applied to the field:
$('#eventlist_c_label').html('{$mod_strings['LBL_EVENTLIST']}: ');

Browser freezing for a couple of second

When the following codes are running, it makes the browser freeze for a couple of secondes.
How could i prevent that ? Thanks
function rsfp_changePage(formId, page, totalPages, validate)
{
if (validate)
{
var form = rsfp_getForm(formId);
if (!ajaxValidation(form, page))
return false;
}
for (var i=0; i<=totalPages; i++)
{
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage)
document.getElementById('rsform_' + formId + '_page_' + i).style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage)
{
thePage.style.display = '';
try {
eval('if (typeof rsfp_showProgress_' + formId + ' == "function") rsfp_showProgress_' + formId + '(' + page + ')');
}
catch (err) { }
}
}
...
You will find the form on http://www.ocsl.ch/dev
username : stackoverflow /
password : stackoverflow
Login first and then go to http://www.ocsl.ch/dev/sejour-linguistique/adultes/demande-d-offre-en-ligne
Once on this page, click on the green button "suivant" and you will see that it freezes for a very little will.
Below the content form the script.js file which contain the ajaxvalidation fonction.
Hope that helps a bit. Please ask if you need any thing else that may help.
function refreshCaptcha(componentId, captchaPath)
{
if(!captchaPath) captchaPath = 'index.php?option=com_rsform&task=captcha&componentId=' + componentId;
document.getElementById('captcha' + componentId).src = captchaPath + '&' + Math.random();
document.getElementById('captchaTxt' + componentId).value='';
document.getElementById('captchaTxt' + componentId).focus();
}
function number_format(number, decimals, dec_point, thousands_sep)
{
var n = number, prec = decimals;
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
var abs = Math.abs(n).toFixed(prec);
var _, i;
if (abs >= 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec);
} else {
s = s.replace('.', dec);
}
return s;
}
function buildXmlHttp()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function ajaxValidation(form, page)
{
try
{
var el = form.elements.length;
}
catch (err)
{
form = this;
}
var xmlHttp = buildXmlHttp();
var url = 'index.php?option=com_rsform&task=ajaxValidate';
if (page)
url += '&page=' + page;
var params = new Array();
var submits = new Array();
var success = false;
var formId = 0;
for (i=0; i<form.elements.length; i++)
{
// don't send an empty value
if (!form.elements[i].name) continue;
if (form.elements[i].name.length == 0) continue;
// check if the checkbox is checked
if (form.elements[i].type == 'checkbox' && form.elements[i].checked == false) continue;
// check if the radio is selected
if (form.elements[i].type == 'radio' && form.elements[i].checked == false) continue;
if (form.elements[i].type == 'submit')
{
submits.push(form.elements[i]);
form.elements[i].disabled = true;
}
// check if form is a dropdown with multiple selections
if (form.elements[i].type == 'select-multiple')
{
for (var j=0; j<form.elements[i].options.length; j++)
if (form.elements[i].options[j].selected)
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].options[j].value));
continue;
}
if (form.elements[i].name == 'form[formId]')
formId = form.elements[i].value;
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value));
}
params = params.join('&');
xmlHttp.open("POST", url, false);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
var success = true;
if (xmlHttp.responseText.indexOf("\n") != -1)
{
var response = xmlHttp.responseText.split("\n");
// All spans set to no error
var ids = response[0].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
document.getElementById('component'+ids[i]).className = 'formNoError';
// Show errors
var ids = response[1].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
{
document.getElementById('component'+ids[i]).className = 'formError';
success = false;
}
if (response.length == 4)
{
page = parseInt(response[2]) - 1;
totalPages = parseInt(response[3]);
rsfp_changePage(formId, page, totalPages, false);
}
for (var i=0; i<submits.length; i++)
submits[i].disabled = false;
}
if (success == false && document.getElementById('rsform_error_' + formId))
{
try {
document.getElementById('rsform_error_' + formId).style.display = '';
}
catch (err) { }
}
return success;
}
function rsfp_addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
function rsfp_getForm(formId)
{
var formIds = document.getElementsByName('form[formId]');
for (var i=0; i<formIds.length; i++)
{
if (parseInt(formIds[i].value) != parseInt(formId))
continue;
var form = formIds[i].parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
while (form.parentNode)
{
form = form.parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
}
}
}
Thanks #JuanMendes, it didn't help unfortunately. I made some reaserch to find out how could I modify the codes to send an asynchronous request but I didn't succeed. In the ajaxValidation fonction, there is
xmlHttp.open("POST", url, false);
if I change it to
xmlHttp.open("POST", url, true);
it should then be an asynchronous request, isn't it.
When I tested it, it didn't freeze the browser, however it doesn't show the error if fields are not filled up on the form. Instead, it validates which is not mean to be. Any help ?
As IAbstractDownvoteFactory mentioned, you're probably calling ajax in synchronous mode, which means exactly that, freeze the screen while you're waiting for the network call.
The reason it looks that way is that your ajaxValidation is returning a value. Typically, you would send an asynchronous request and your ajaxValidation would take a callback. Then the UI won't hang waiting for the XHR.
// This is an improvement over what you had
// Still poor code, since it's hard to tell what the function is doing
function rsfp_changePage(formId, page, totalPages, validate)
{
var form = rsfp_getForm(formId);
if (validate) {
// Change your AJAX validation function to take a callback, which passes the return
// value (asynchronous) instead of relying on a return value (synchronous)
ajaxValidation(form, page, function(validationResult){
if (validationResult) {
showProgress();
}
});
} else {
showProgress();
}
function showProgress() {
for (var i=0; i<=totalPages; i++) {
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage) {
thePage .style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage) {
thePage.style.display = '';
// Don't use eval, use window and bracket to avoid it
var func = window["rsfp_showProgress_" + formId];
if (typeof func == "function") {
func(page);
}
}
}
}
}

Categories

Resources