if statements being skipped even when both expressions are true - javascript

I have a webpage that populates a table with arrays. It has a doClick function so that when a user clicks on a cell it passes the row and column of the cell to the function. Example cell: onclick="doClick(0,1)"
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if ((top != -1) && (cells[top][col].innerHTML = ""))
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && (cells[row][right].innerHTML = ""))
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML = ""))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((left != -1) && (cells[row][left].inn = ""))
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
. The problem is, even if both if expressions are true, the if statement is being skipped and it's falling through to the else statement. I've desk checked it and run it through the developer tools and checked values. A statement that was true on both expressions was skipped. Any suggestions?

cells[row][right].innerHTML = ""
is wrong. You are missing the double (triple) =.
The correct way should be...
cells[row][right].innerHTML === ""

It looks like maybe there are a few typos or misconceptions in your code.
A quick note about Conditions in an IF statement
A statement like (cells[top][col].innerHTML = "") as a condition will always return true as this is setting cells[top][col].innerHTML as "" or at least instantiating the variable. So, the proper condition to test absolutely true or false would be (cells[top][col].innerHTML === ""). However, you can get away with not even doing that and simply replace (cells[top][col].innerHTML = "") with cells[top][col].innerHTML. You may run into some other issues though is the variable is not instantiated already, either way. I would wrap the latter logic in an IF statement to check if cells[top][col].innerHTML is even instantiated.
To fix this, check out the following modifications I have made to your code.
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if(typeof cells[top][col].innerHTML !== 'undefined' $$ cells[top][col].innerHTML !== null)
{
if ((top != -1) && cells[top][col].innerHTML !== '')
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && cells[row][right].innerHTML !== '')
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
else if (typeof cells[row][left].inn !== 'undefined' && (left != -1) && cells[row][left].inn !== '')
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
An example working to demonstrate the above code
var testVar1 = '';
var testVar2 = 'Hello';
// var testVar3; <- Left this un-instantiated to test existance
// Testing if a var is empty but exists
if(typeof testVar1 !== 'undefined' && testVar1 !== null){
if(testVar1 !== ''){
alert('testVar1 has a value!');
}{
alert('testVar1 does not have a value!');
}
}
// Testing if a var is empty but exists
if(typeof testVar2 !== 'undefined' && testVar2 !== null){
if(testVar2 !== ''){
if(testVar2 === 'Hello'){
alert('testVar2 has a value! Value: ' + testVar2);
}{
alert('testVar2 has a value but it is not the one we expected.');
}
}{
alert('testVar2 does not have a value!');
}
}
// Test existance
if(typeof testVar3 !== 'undefined' && testVar3 !== null){
alert('testVar3 exists!');
}else{
alert('testVar3 does not exist!');
}

Related

Cannot read property 'value' of null on simple var assignment: var goToThis = "";

I'm getting a javascript error Cannot read property 'value' of null on simple var assignment var goToThis = "";
// It is the second function that has the error.
function nextFocus(tLast) {
var goToThis = "";
var val = 0;
if(tLast === 'activity') {
if(document.getElementById('[Slip]Note').value === "") {
document.getElementById('[Slip]Note').value = document.getElementById('[Slip]Activity').value;
}
}
if((tLast === 'activity') && (fLedes === true)){
document.getElementById('[Slip]Task No').focus();
} else if((tLast === 'activity') && (fLedes === false)){
goToThis = 'billableHrs';
} else if(tLast === 'expense'){
goToThis = 'priceAdjustment';
} else if((tLast === 'task') && (initialSlipType === 'time')){
goToThis = 'billableHrs';
} else if((tLast === 'task') && (initialSlipType === 'expense')){
goToThis = 'priceAdjustment';
}
if(goToThis === 'billableHrs') {
val = getReal(document.getElementById("[Slip]Billable Hrs"));
if(val === 0) {
document.getElementById("[Slip]Billable Hrs").value = '';
//alert('[Slip]Billable Hrs: '+val);
}
document.getElementById('[Slip]Billable Hrs').focus();
} else if (goToThis === 'priceAdjustment') {
val = getReal(document.getElementById("[Slip]Price Adjustment"));
if(val === 0) {
document.getElementById("[Slip]Price Adjustment").value = '';
//alert('[Slip]Price Adjustment: '+val);
}
document.getElementById('[Slip]Price Adjustment').focus();
}
}
This error was solved by correcting the spelling of an HTML element involved with this function call.
Safari pointed to the correct error line.
Chrome would not point to the correct error line.
Check opening and closing curly braces {} on all functions of the page. Sometimes {} mismatch ,also gives weird errors. Also try '' instead of "";

Getting an Unknown CORS error in Odoo-12 POS UI Book Orders

I am getting this error on POS UI I really need help because I don't understand the error
I am using the Book Order module and I often get this error like 1 in 10 book orders
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at child.add_product (point_of_sale.assets.js:493)
at Class.line_select (point_of_sale.assets.js:429)
at HTMLButtonElement.<anonymous> (point_of_sale.assets.js:425)
at HTMLTableSectionElement.dispatch (web.assets_common.js:892)
at HTMLTableSectionElement.elemData.handle (web.assets_common.js:865)
here's how I modified the add_product function
add_product: function(product, options){
var can_add = true;
var changes = this.pos.get_order();
var self = this;
if(changes.selected_orderline){
if(changes.selected_orderline.order){
if(changes.selected_orderline.order.quotation_ref){
if(changes.selected_orderline.order.quotation_ref.book_order){
can_add= false;
}
}
}
}
if (can_add){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new POSInheritmodel.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.discounted_amount !== undefined){
line.set_discount_amount(options.discounted_amount);
}
if(options.discount_percentage !== undefined){
line.set_if_discount_percentage(options.discount_percentage);
}
if(options.discount_amount !== undefined){
line.set_if_discount_amount(options.discount_amount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
if(options.uom !== undefined || options.uom !== false){
line.set_unit_id(options.uom);
}
if(options.is_board_feet !== undefined && options.is_board_feet){
line.set_is_board_feet(true);
line.set_length(product.length);
line.set_thickness(product.thickness);
line.set_width(product.width);
// console.log(product.length);
}else if(options.is_board_feet !== undefined && !options.is_board_feet){
line.set_is_board_feet(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_board_feet){
line.set_is_board_feet(true);
line.set_length(product.length);
line.set_thickness(product.thickness);
line.set_width(product.width);
}
}
}
}
if(options.is_lineal_feet && options.is_lineal_feet !== undefined){
line.set_is_lineal_feet(true);
line.set_length(product.length);
// console.log(product.length);
}else if(options.is_lineal_feet !== undefined && !options.is_lineal_feet){
line.set_is_lineal_feet(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_lineal_feet){
line.set_is_lineal_feet(true);
line.set_length(product.length);
}
}
}
}
if(options.is_lineal_meter && options.is_lineal_meter !== undefined){
line.set_is_lineal_meter(true);
line.set_length(product.length);
// console.log(product.length);
}else if(options.is_lineal_meter !== undefined && !options.is_lineal_meter){
line.set_is_lineal_meter(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_lineal_meter){
line.set_is_lineal_meter(true);
line.set_length(product.length);
}
}
}
}
if(options.with_base_price){
line.set_with_base_price(true);
if(options.base_price_discount !== undefined){
line.set_base_price_discount(options.base_price_discount);
}
if(options.markup !== undefined){
line.set_markup(options.markup);
}
// console.log(product.length);
}
if(options.is_weight !== undefined && options.is_weight){
line.set_is_weight(true);
line.set_weight_receipt_display(options.base_weight);
}else if(options.is_weight !== undefined && !options.is_weight){
line.set_is_weight(false);
if(options.base_weight !== undefined && options.base_weight != 0){
line.set_weight_receipt_display(options.base_weight);
}else{
line.set_weight_receipt_display(product.weight);
}
}else{
if(options.base_weight !== undefined && options.base_weight != 0){
line.set_weight_receipt_display(options.base_weight);
}else{
line.set_weight_receipt_display(product.weight);
}
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_weight){
line.set_is_weight(true);
}
}
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
}else{
self.pos.gui.show_popup('error',{
title :_t('Modification Restricted'),
body :_t('Modification is not allowed for booked orders.'),
});
}
},
this is all that I can give I didn't try anything to fix this because I don't really know where to start any help is very much appreciated thank you.

Textarea resize when field is empty

I have problem with this code
I will create a JS addon to resize textarea when textfield is empty,
i think this code is good but not work for me :(
reason = document.getElementById('reason').value !== "";
causes = document.getElementById('causes').value !== "";
corrections = document.getElementById('corrections').value !== "";
comment = document.getElementById('comment').value !== "";
var disabled = $('form-control').is(':disabled') == true;
if (disabled && reason){
$("#reason").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && causes){
$("#causes").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && corrections){
$("#reason").attr("rows","5");
}
var disabled = $('form-control').is(':disabled') == true;
if (disabled && comment){
$("#reason").attr("rows","5");
}
You need to not repeat yourself (DRY)
let anyFilled = $("#reason,#causes,#corrections,#comment").filter(function() {
return this.value != "";
}).length>0;
if ($('form-control').is(':disabled') && anyFilled) {
$("#reason").attr("rows", "5");
}
Why are you redeclaring disabled so many times? especially since its the same expression each time? Just declare it once and make sure you brush up on DRY programming
var reason = $('#reason').val() !== "";
var causes = $('#causes').val() !== "";
var corrections = $('#corrections').val() !== "";
var comment = $('#comment').val() !== "";
var disabled = $('form-control').is(':disabled') == true;
if (disabled) {
if (causes || corrections || comment) {
$("#reason").attr("rows", "5");
}
}

Faster Evaluating IF Condition of JavaScript

Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')

String comparison not as expected

I have written the following code looking for a string token in an array.
var parseCSVLines = function(lines) {
var valueObj = {};
var delim = ',';
var isLayer = false;
var isGroup = false;
for(var i = 0; i < lines.length; i++){
//skips CR/CF lines
if(!lines[i]) continue;
//only data lines reach this loop
var data = lines[i].split(delim);
/*********looks for tag*************/
if(data[0] == '#L' || data[0] == '#l'){
//on occasions, data[0] is '#L' or '#G' still execution reaches here
isLayer = true;
}else if(data[0] == '#G' || data[0] == '#g'){
isGroup = true;
}else{
if(isLayer){
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
}
else if(isGroup){
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
}
return valueObj;
};
I loop through lines and mark next line to get data. Weirdly when data[0] is '#L' and '#G', first if statement is executed. What have I done wrong?
The if statement is fine, even if you have data[0]='#G#L'...it will never go into data[0]=='#L'||data[0]=='#l'
On my mind you are stuck in the logic-
if (data[0] == '#L' || data[0] == '#l') {
isLayer = true;
//isGroup=false; you should toggle isGroup
} else if (data[0] == '#G' || data[0] == '#g') {
isGroup = true;
//isLayer=false; you should toggle isLayer
} else { //do you want else here??? This would pick the value of isLayer or isGroup according to previous line processed but not the value according to current line being processed.
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
Example:
line1: '#L,hi'
line2:'#G,hi'
line3:'hi'
processing first line will set isLayer=true;
processing second line will set isGroup=true;//remember isLayer is still true - you haven't set it to false;
processing third line will trigger your else part...and get into first condition where if(isLayer) will be true
To make it work:
//update isLayer and isGroup for every iteration to keep the logic inline
isLayer=(data[0] == '#L' || data[0] == '#l');
isGroup=(data[0] == '#G' || data[0] == '#g');
if(!isLayer && !isGroup) {
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
Try this:
if(data[0] == "#l" || data[0] == "#L") {
if(data[0].search("#g") != -1 || data[0].search("#G") != -1){
}else{
isLayer = true;
}
}else if(data[0] == "#g" || data[0] == "#G"){
if(data[0].search("#l") != 0 || data[0].search("#L") != 0){
}else{
is group = true;
}
}
You see, what you weren't doing was checking if both were present. What my code does is checks that
The item is #g or #l
The item is not the opposite as well.
This ensures that one, and only one option is chosen.
Good day, And good luck.

Categories

Resources