"IF ELSE" Javascript not working - javascript

A) I have a first function which works very well :
if(onlyUs == '1' && idUser == '0'){
obj.after(jQuery('<div />').css({'clear':'both'}).addClass('kklike-msg').text('Only registered users can vote.'));
setTimeout(function(){
jQuery('.kklike-msg').fadeOut('normal');
},3000);
return false;
}
B) So I thought I could do the following thing :
if(idUser == '0'){
if(action == 'like'){
var ajaxAction = 'add_like';
}else{
var ajaxAction = 'remove_like';
}
}else{
if(action == 'like'){
var ajaxAction = 'add_like';
window.open('http://mywebsite.com/like')
}else{
var ajaxAction = 'remove_like';
window.open('http://mywebsite.com/remove')
}
}
C) Knowing that the original function is simply (works well):
if(action == 'like'){
var ajaxAction = 'add_like';
}else{
var ajaxAction = 'remove_like';
}
But B) is not working. In both condition (Login or not), the new window is going to open.
Do you have a solution ?

Without knowing the type of idUser, it is difficult to tell what the problem is, but the most likely culprit is the use of == for comparison instead of ===. JavaScript will convert the variables being compared into similar types when using ==, which can cause some very unpredictable results in your case.
I recommend writing your code like the following. If this still does not work as you expected, you should investigate what the value of idUser actually is. It may not be a string which would be the cause of your problem.
if (idUser === '0') {
if(action === 'like') {
var ajaxAction = 'add_like';
} else {
var ajaxAction = 'remove_like';
}
} else {
if (action === 'like') {
var ajaxAction = 'add_like';
window.open('http://mywebsite.com/like');
} else {
var ajaxAction = 'remove_like';
window.open('http://mywebsite.com/remove');
}
}
For a very simple example of why you should use ===, see this blog post:
http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

Related

How to set CRM javascript value to null?

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

is this the right way to pull booleans from localstorage?

function loadChoice(key, varToStore) {
if (window.localStorage.getItem(key) === "true") {
varToStore = true;
}
else if (window.localStorage.getItem(key) === "false") {
varToStore = false;
}
else {
varToStore = window.localStorage.getItem(key);
}
}
I think I found a way to pull booleans (that got converted to strings before) from the web-browser localstorage.
can anyone confirm or have a better method ?

true == false evaluates to true somehow?

I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.

Refactor javascript function

:) i have created some javascript, it works well, my javascript knowledge limit me to create some compact and light script.
this is some sub menu javascript of aspx framework, here it it the script :
if (name === 'diensten/consultancy')
{
activeOne();
}
else if (name === 'diensten/maatwerk')
{
activeTwo();
diesntenActive();
}
else if (name === 'diensten/outsourcing')
{
activeThree();
diesntenActive();
}
else if (name === 'diensten/opleidingen')
{
activeFour();
diesntenActive();
}
else if (name === 'diensten/implementaties')
{
activeFive();
diesntenActive();
}
else if (name === 'support')
{
activeOne();
supportActive();
}
else if (name === 'support/contact')
{
activeTwo();
supportActive();
}
else if (name === 'support/download')
{
activeThree();
supportActive();
}
else if (name === 'overOns')
{
activeOne();
overOnsActive()
}
else if (name === 'overOns/cebes')
{
activeTwo();
overOnsActive()
}
else if (name === 'overOns/partner')
{
activeThree();
overOnsActive();
}
else if (name === 'overOns/vacatures')
{
activeFour();
overOnsActive();
}
else if (name === 'fireman')
{
productenActive();
}
else if (name === 'prio')
{
productenActive();
}
else if (name === 'firstwatch')
{
productenActive();
}
else if (name === 'firstwatchOnline')
{
productenActive();
}
else if (name === 'cebesFrame')
{
productenActive();
}
else if (name === 'cms')
{
productenActive();
}
return false
I am sure there is a way to shorten this javascript, not too urgent, just for give me more knowledge about javascript. Any suggestion are welcome. Thanks.
A start would be to use a switch statement instead of a long if/else tree.
switch (name) {
case 'diensten/consultancy':
activeOne ();
break;
case 'diensten/maatwerk':
activeTwo ();
diesntenActive ();
break;
...
case 'cms':
productActive ();
break;
default:
console.log ("No handler found for '" + name + "'!");
}
An alternative method is to use an objectin which you define functions and associate them to relevant keys.
var func_map = {
'diensten/consultancy': function () {
activeOne ();
},
'diensten/maatwerk': function () {
activeTwo ();
diesntenActive ();
},
'diensten/outsourcing': function () {
activeThree();
diesntenActive();
},
...
'cms': function () {
productenActive();
}
};
if (name in func_map) func_map[name] ();
else console.log ("No handler found for name = '" + name + "'!");
You have a perfect situation for a lookup table. You have a whole bunch of possibilities for the name and your action for each name is just one or more simple function calls.
That means you can use a lookup table. You put the value for name as the key and an array of function names to call for that name. One lookup in the table gets you an array of functions to call and you loop through the array to call each one. This has the advantage that to add more items, you just add a new line to the table without writing any additional lines of code:
var lookup = {
"cms": [productenActive],
"cebesFrame": [productenActive],
"firstWatchOnline": [productenActive],
"fireman": [productenActive],
"firstwatch": [productenActive],
"prio": [productenActive],
"overOns/vacatures": [activeFour, overOnsActive],
"overOns/partner": [activeThree, overOnsActive],
"overOns/cebes": [activeTwo, overOnsActive],
"overOns": [activeOne, overOnsActive],
"support/download": [activeThree, supportActive],
"support/contact": [activeTwo, supportActive],
"support": [activeOne, supportActive],
"diensten/implementaties": [activeFive, diesntenActive],
"diensten/opleidingen": [activeFour, dienstenActive],
"dienstenout/outsourcing": [activeThree, dienstenActive],
"diensten/maatwerk": [activeTwo, dienstenActive],
"diensten/consultancy": [activeOne]
};
var fns = lookup[name];
if (fns) {
for (var i = 0; i < fns.length; i++) {
fns[i]();
}
}
Here's my attempt. Its not the best in that its very specialized to your case. However, it does provide a lot of dynamic calling and code reuse.
var subPage = {
'diensten' : ['consultancy', 'maatwerk', 'outsourcing', 'opleidingen', 'implementaties'],
'support' : [undefined, 'contact', 'download'],
'overOns' : [undefined, 'cebes', 'partner', 'vacatures'],
}
var others = ['fireman', 'prio', 'firstwatch', 'firstwatchOnline', 'cebesFrame', 'cms'];
var active = [activeOne, activeTwo, activeThree, activeFour, activeFive];
var addr = name.split('/');
if (subPage[addr[0]]){
var index = subPage[addr[0]].indexOf(addr[1]);
if (index != -1){
active[index]();
if (addr[1] !== 'consultancy') // Special case
this[adder[0]+'Active'](); // Assuming this refers to the scope where diesntenActive() lives
}
} else if (others.indexOf(addr[0]) != -1){
productenActive();
}
return false;
Anyways, this probably over-complicates things. I would still recommend you either use a switch statement or a lookup table, unless you really really care about reducing your script size. Only in that case might you consider my very specialized approach.

Some problem with jquery form

This my code:
$(document).ready(function() {
$('.submit').click(function() {
var answer_text = $("#answer_text").val();
if (answer_text === '' || undefined === $("input[name='answer[scale]']:checked").val()) {
alert('error!!');
return false;
}
else {
alert('yeah! cool baby!');
}
}
});
Problem: jQuery doesn't see the ||. I don't know what to do. I tried to do something like:
if
else if
else
or
if
else
if
else
Don't know what to do. please help me, maybe some error and mistakes with OR operator? or what?
To know if no checkbox was checked just use the length, no need to mess with the value:
if (answer_text === '' || $("input[name='answer[scale]']:checked").length === 0) {
//answer text is empty and no answer scale checkbox was checked
}
i guess what you wanted to do is
if (answer_text === '' || $("input[name='answer[scale]']:checked").val()==="undefined"){
you have got the operands on the wrong side of the operator
Try to wrap it in proper braces and check.
if ((answer_text === '') || (undefined === $("input[name='answer[scale]']:checked").val()))
$(document).ready(function() {
$('.submit').click(function() {
var answer_text = $("#answer_text").val();
if (answer_text == ''){
if ( undefined === $("input[name='answer[scale]']:checked").val()){
alert('error!!');
return false;
}
else{
alert('yeah! cool baby!');
}
}
else{
alert('yeah! cool baby!');
}
}
}
This is not the fastest way but it will do it...

Categories

Resources