JavaScript array - unexpected token - javascript

Hello I'm trying to create an array of errors, and display them at once. Something like this.
if (!first_name) {
var error[] = "Заполните Фамилию";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
var error[] = 'Заполните Имя';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
var error[] = 'Заполните Отчество';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
var error[] = 'Заполните Курс';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
var error[] = 'Заполните хотябы один предмет';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
and then
if(error.length > 0) {
$(".errors").html(error);
}
But i'm getting an error Uncaught SyntaxError: Unexpected token ]
What am i doing wrong?

Two main problems - the error array was being repeatedly and incorrectly declared, and the display of the resulting array was being handled incorrectly. Here's a fix for both problems....
var error = []; // initialise empty array
if (!first_name) {
error.push( "Заполните Фамилию");
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error.push( 'Заполните Имя');
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error.push('Заполните Отчество');
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error.push( 'Заполните Курс');
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error.push( 'Заполните хотябы один предмет');
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
// you will need to join the elements together somehow before displaying them
if (error.length > 0) {
var data = error.join( '<br />');
$(".errors").html(data);
}
You might also want to look at using the toggleClass function instead of add/remove, but that's up to you

All of these lines contain syntax errors:
var error[] = ...
because error[] is not a valid JavaScript identifier. Remove the []s. The closest valid variable name would be error instead of error[].
This kind of error is made painfully evident when you run your code through a JavaScript linter tool.

You are confusing JavaScript with PHP.
This is incorrect way to declare an array:
var error[] = 'Заполните Отчество';
rather:
var error = new Array();
or
var error = [];

To append values into an array using javascript :
var error = [];
error.push('Error 1');
error.push('Error 2');
Then, to display them :
$('.errors').html(
error.join('<br/>') // "Error 1<br/>Error 2"
);
Doc : push, join.

You can display all error message at once like that
var error=''
if (!first_name) {
error += "Заполните Фамилию.<br />";
$('#first_name').addClass('error');
} else {
$('#first_name').removeClass('error');
}
if (!second_name) {
error += 'Заполните Имя<br />';
$('#second_name').addClass('error');
} else {
$('#second_name').removeClass('error');
}
if (!last_name) {
error += 'Заполните Отчество<br />';
$('#last_name').addClass('error');
} else {
$('#last_name').removeClass('error');
}
if (!course) {
error += 'Заполните Курс<br />';
$('#course').addClass('error');
} else {
$('#course').removeClass('error');
}
if (!math && !programming && !english && !history) {
error +='Заполните хотябы один предмет<br />';
$('#math,#programming,#english,#history').addClass('error');
} else {
$('#math,#programming,#english,#history').removeClass('error');
}
if (error != '') {
$(".errors").html(error);
return false;
}
error is a one variable where i stored all the error and display at once on the screen.

Related

gettin this error in node jd error: TypeError: Cannot read property '0' of undefined

hi i am trying to implement a local orderbook using the binance api however i keep getting this error every now and then it does not always happen but if it does it will happen early on please help
this is the main file that runs calling an exports function from an external file to process the data coming from the web socket on message
wsClient.subscribeSpotDiffBookDepth("btcusdt");
wsClient.on('message', (data) => {
// Setup and process order book information
order_book.update_orderbook(data);
if(order_book.ready === 1){
order_book.get_orderbook_history();
}
});
wsClient.on('error', err => {
/* handle error */
console.log("this is it 2 " + err);
});
wsClient.on('close', () => {
/* ... */
});
exports function in external file
exports.update_orderbook = function(data) {
if(data.e == "depthUpdate"){
if(this.ready === 0){
this.ready = 1;
console.log("Stage 1 in play");
}else{
this.buffer += data;
}
if(this.ready === 2 && this.asks != null && this.bids != null){
if(undefined !== this.asks && undefined !== this.bids && undefined !== data.a && undefined !== data.b){
if(data.U <= this.lastUpdateId + 1 && data.u >= this.lastUpdateId + 1){
// error is coming from calling this function-------------------------------------------------------
var temp_array1 = sort_array(this.asks, data.a);
var temp_array2 = sort_array(this.bids, data.b);
this.asks = temp_array1;
this.bids = temp_array2;
this.lastUpdateId = data.u;
console.log("Stage 3");
}
}
}else{
this.buffer += data;
}
}
}
function to sort and update the array
function sort_array(array1, array2){
for(let x in array2){
if(array2[x][1] == 0){
for(let i in array2){
if(array1[i][0] === array2[x][0]){
array1.splice(i, 1);
}
}
}else{
var in_array = false;
for(let i in array1){
// this seems to be the problem area---------------------------------------------------------
if(array1[i][0] === array2[x][0]){
array1[i] = array2[x];
in_array = true;
}
}
if(!in_array){
array1.push(array2[x]);
}
}
}
return array1;
}
error log

Unexpected token ; when defining Boolean variable

I am setting up a TF2 trading bot that can price check. I get an error when defining a boolean for if it is priced in keys or not.
I have tried just replacing isKeys with data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys" in the if statement but get an error for the closing bracket in the if statement.
var data = {
};
var currencies = {
};
requestify.get('https://backpack.tf/api/IGetPrices/v4?raw=1&since=0&key=5cf17c256780725011449df2')
.then(function(response) {
data = response.getBody().response.items;
console.log(data["Australium Tomislav"].prices["11"].Tradable.Craftable);
}
);
requestify.get('https://backpack.tf/api/IGetCurrencies/v1?key=5cf17c256780725011449df2')
.then(function(response) {
currencies = response.getBody().response.currencies;
}
);
function toRef(keys, high) {
if (high) {
if (currencies.keys.price.value_high != undefined){
return currencies.keys.price.value_high * keys
} else {
return currencies.keys.price.value * keys
}
} else {
return currencies.keys.price.value * keys
}
}
function getPrice(item, high) {
var name = item.market_name;
var quality = item.tags[0].name;
var baseName = name.replace(quality + " ", "");
var qualityId = itemQualities[quality];
var isCraftable = true;
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
for (i = 0;i < item.description.length;i++) {
if (item.description[i].value == '( Not Usable in Crafting )') {
isCraftable = false;
}
}
if (high) {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high], true);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high];
}
} else {
if (isKeys) {
return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value], false);
} else {
return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value];
}
}
}
`
G:\BOT\bot.js:106
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys";
^
SyntaxError: Unexpected token ;
is the error I get
TL;DR: You are missing a ] on the erred line. And you have extra ] on the below if(high){...} lines.
You are missing a square bracket ] in the line,
var isKeys = ... as the other answers suggest.
Now, we don't know the data structure so it can be,
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0].currency*]*
or
data[baseName]
.prices[qualityId.toString()]
.Tradable[craftable[isCraftable.toString()][0]*]*.currency
But Also,
You have extra Square braces on the lines,
if (high) {
if (isKeys) {
/*--here>>*/return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high, true);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value_high;
}
} else {
if (isKeys) {
/*--here>>*/ return toRef(data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value, false);
} else {
/*--here>>*/return data[baseName].prices[qualityId.toString()].Tradable[isCraftable.toString()][0].value;
}
}
Again we don't know the exact data structure.
You're missing a square bracket for Tradable
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()]][0].currency == "keys";
In that line a square-bracket-close (]) is missing.
Your line is:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"; // Error here
You open a bracket at .Tradable[ but it isn't closed until the end of that line.
The compiler expects a ] but finds a ;.
I am not familar with the API you are using but I suppose the following would fix the error:
var isKeys = data[baseName].prices[qualityId.toString()].Tradable[craftable[isCraftable.toString()][0].currency == "keys"]; // << Notice the bracket before your semicolon

Javascript Loop Not Finished before If Statement Runs

I have been stuck on this issue for some time now. I am calling an API - get the results just fine. I am saving the values to an array. The problem which I am encountering is trying to get specific values from the array. I have a for in loop running which takes time, so when the if statement is ran the loop hasn't reached that value. If I use Postman, I see that the value exists, its just the loop doesn't execute in time. Here is my code:
var msg = {};
var embed = {};
var link = {};
var msgIn = [];
var rel = [];
return SkypeService.getEvent(msg).then(function (result) {
msg.eventsNext = result._links.next.href;
if (result && result.sender && result.sender.length > 0) {
if (result.sender) {
for (var item in result.sender) {
var event = result.sender[item].events;
for (var key in event) {
embed = event[key]._embedded;
msgIn.push(embed);
}
for (var key in event) {
link = event[key].link;
rel.push(link);
}
// console.log(Object.entries(msgIn))
if(rel['rel'] == 'message') {
console.log("message is there")
if(msgIn.message) {
console.log("links exist")
if(msgIn.message.direction == "Incoming") {
console.log("direction is there")
msg.participant = msgIn.message._links.participant.href;
msg.contMsg = msgIn.message._links.messaging.href;
msg.msgIn = msgIn.message._links.plainMessage.href;
break;
}
}
}
if(rel['rel'] == "messagingInvitation"){
console.log("invite there")
if(msgIn.messagingInvitation && msgIn.messagingInvitation.state !== "Failed") {
console.log("invite link")
if(msgIn.messagingInvitation.direction == "incoming") {
console.log("direction invite")
msg.msgInviteState = msgIn.messagingInvitation._links.state;
msg.acceptInvite = msgIn.messagingInvitation._links['accept'].href;
msg.msgIn = msgIn.messagingInvitation._links.message.href;
break;
}
}
}
if(rel['rel'] == 'messaging') {
console.log('messaging there')
if(msgIn.messaging) {
if(msgIn.messaging.state == "Disconnected") {
console.log("msgn Disconnected")
msg.addMsg = msgIn.messaging._links.addMessaging.href;
break;
}
}
}
}
}
}
console.log(msg)
})
Also, I've attached a screenshot of my local host printing the msgIn which shows that the keys exists.
When I test the code running sails lift, I can see that msgIn prints a couple of times each one increasing in length. This is what makes me think the for loop has not completed by the time the if statement runs.
Please help - I really need for this to be resolved. I need to capture the links so that I can use those in the next step.
Thanks.
I have resolved my issue by making changes to the code. Here is the new version:
return
SkypeService.getEvent(msg).then(function
(result) {
msg.eventsNext = result._links.next.href;
if (result.sender) {
for (var item in result.sender) {
var event = result.sender[item].events;
for (var key in event) {
embed = event[key]._embedded;
link = event[key].link;
};
if(link['rel'] == 'message') {
console.log("message is there")
if(embed.message) {
console.log("links exist")
if(embed.message.direction == "Incoming") {
console.log("direction is there")
msg.participant = embed.message._links.participant.href;
msg.contMsg = embed.message._links.messaging.href;
msg.msgIn = embed.message._links.plainMessage.href;
break;
}
}
};
if(link['rel'] == "messagingInvitation"){
console.log("invite there")
if(embed.messagingInvitation) {
console.log("invite link")
if(embed.messagingInvitation.direction == "incoming") {
console.log("direction invite")
msg.msgInviteState = embed.messagingInvitation._links.state;
msg.acceptInvite = embed.messagingInvitation._links['accept'].href;
msg.msgIn = embed.messagingInvitation._links.message.href;
break;
}
}
};
if(link['rel'] == 'messaging') {
console.log('messaging there')
if(embed.messaging) {
if(embed.messaging.state == "Disconnected") {
console.log("msgn Disconnected")
msg.addMsg = embed.messaging._links.addMessaging.href;
break;
}
}
};
console.log(msg)
};
};
});
I have removed the result validation and simplified the for (var key in event) to handle both operations in one. Also, I have removed the arrays which I was pushing the values into as I was not using that. That may have been the time consuming factor which was preventing me from getting the direction validated.

I get an error while running an JS script with capybara/selenium/ruby

I am new to Automation, I am using Selenium,ruby,capybara to execute this JS script and I get this error message,any help appreciated TIA
Error message
Selenium::WebDriver::Error::UnknownError: unknown error: Runtime.evaluate threw exception: SyntaxError: Invalid or unexpected token
page.execute_script('(function() {
function renderField($el, mode) {
var limitMet,
field = $el.data(\'add-field\'),
section = $el.data(\'section\');
window.DADI.editor.freeSections.forEach(function(freeSection) {
if (section === freeSection.name) {
freeSection.fields.forEach(function(sectionField) {
if(field === sectionField.source) {
var count = $(\'#section-\' + section).find(\'[data-field="\'+field+\'"]\').length;
if (sectionField.max && count >= sectionField.max) {
limitMet = true;
}
}
}.bind(this))
}
}.bind(this))
if (!limitMet) {
if (!window.DADI.editor.types[field]) return false;
var template = window.DADI.editor.types[field]._local.layouts.article[0].replace(\'.dust\', \'\');
var html;
if (template) {
var templateData = window.DADI.editor.types[field];
templateData.params = window.DADI.editor.params,
templateData.free = true;
templateData.fieldName = field;
window.DADI.render.render(\'fields/\' + template, \'#section-\' + section, templateData, {mode: mode}, function (err, out) {
if (err) {
html = err;
} else {
html = $(out);
if ($(\'.selectize\', html) && $(\'.selectize\', html).length) {
dadiSelect($(\'.selectize\', html));
}
if (html.attr(\'data-ql-editable\')) {
createEditor(html, 0);
html.focus();
}
var fieldType = window.DADI.editor.types[field]._remote._publishType;
var handler = window.DADI.editor.handlers[fieldType];
if (handler && (typeof handler.initialiseField === \'function\')) {
handler.initialiseField(html);
}
}
});
return html;
}
}
}
# This takes the button (source) element and drops it into the target area and subsequently renders the appropriate cms fields.
function simulateDragAndDrop(source, target)
{
var $clone = source.clone();
$(target).prepend($clone, target);
if ($clone.hasClass(\'dadiCells-library__element\')) {
renderedHtml = renderField($clone, \'none\');
$clone.replaceWith(renderedHtml);
}
}
var source = $($(\'.dadiCells-library__element\')[1]); #E.g. The hero video button
var target = $(\'#section-hero\'); #The target drop zone.
simulateDragAndDrop(source, target);
})()')
I had a similar issue. What fixed mine was replacing single backslahes / with double backslahes //

unexpected token error for catch javascript

I am banging my head trying to find the error in this code. I have checked it so many times can someone point out where the problem is?
$(function() {
try {
function endswith(str, ends) {
if (ends === '') return true;
if (str == null || ends == null) return false;
str = String(str);
ends = String(ends);
return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
}
var referrer = new URL(document.referrer).domain;
if (endswith(referrer, "xyz.com")) {
$(".logo .logo-external").remove();
} else {
$(".logo .logo-internal").remove();
}
} catch () {}
});
catch (e) {} You missed the variable e
$(function() {
try {
function endswith(str, ends) {
if (ends === '') return true;
if (str == null || ends == null) return false;
str = String(str);
ends = String(ends);
return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
}
var referrer = new URL(document.referrer).domain;
if (endswith(referrer, "xyz.com")) {
$(".logo .logo-external").remove();
} else {
$(".logo .logo-internal").remove();
}
} catch (e) {}
});
As per MDN, try...catch syntax is defined similar to the following:
try {
try_statements
}
...
[catch (exception_var) {
catch_statements
}]
[finally {
finally_statements
}]
This means the exception_var is NOT optional. Otherwise, it would look like this:
...
[catch ([exception_var]) { // Uncaught SyntaxError: Unexpected token )
catch_statements
}]
...

Categories