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 ?
Related
I would like test my Array (input value) before submit my form.
My array with value :
const fields = [
this.state.workshopSelected,
this.state.countrySelected,
this.state.productionTypeSelected,
this.state.numEmployeesSelected,
this.state.startAt
];
I've try this :
_.forEach(fields, (field) => {
if (field === null) {
return false;
}
});
alert('Can submit !');
...
I think my problem is because i don't use Promise. I've try to test with Promise.all(fields).then(());, but i'm always in then.
Anyone have idea ?
Thank you :)
The problem is that even though you're terminating the lodash _.forEach loop early, you don't do anything else with the information that you had a null entry.
Instead of lodash's _.forEach, I'd use the built-in Array#includes (fairly new) or Array#indexOf to find out if any of the entries is null:
if (fields.includes(null)) { // or if (fields.indexOf(null) != -1)
// At least one was null
} else {
// All were non-null
alert('Can submit !');
}
For more complex tests, you can use Array#some which lets you provide a callback for the test.
Live example with indexOf:
const state = {
workshopSelected: [],
countrySelected: [],
productionTypeSelected: [],
numEmployeesSelected: [],
startAt: []
};
const fields = [
state.workshopSelected,
state.countrySelected,
state.productionTypeSelected,
state.numEmployeesSelected,
state.startAt
];
if (fields.indexOf(null) != -1) {
console.log("Before: At least one was null");
} else {
console.log("Before: None were null");
}
fields[2] = null;
if (fields.indexOf(null) != -1) {
console.log("After: At least one was null");
} else {
console.log("After: None were null");
}
You do not need to use promises unless there is an asynchronous operation (for example if you are getting that array from your server).
If you already have that array you can do something like:
// Using lodash/underscore
var isValid = _.every(fields, (field) => (field!==null)}
// OR using the Array.every method
var isValid = fields.every((field)=>(field!==null))
// Or using vanilla JS only
function checkArray(array){
for(var i = 0; i < array.length ; i ++){
if(array[i]===null){
return false;
}
}
return true;
}
var isValid = checkArray(fields);
// After you get that value, you can execute your alert based on it
if(!isValid){
alert('Something went wrong..');
}
Try this simple snippet
var isAllowedToSubmit = true;
_.forEach(fields, (field) => {
if (!field) {
isAllowedToSubmit = false;
}
});
if(isAllowedToSubmit)
alert('Can submit !');
You can do that without library:
if (fields.some(field => field === null)) {
alert('Cannot submit');
} else {
alert('Can submit');
}
You don't need to use lodash, you can do this in simple vanilla javascript. Simply iterate over each field and if an error occurs set your errors bool to true
let errors = false;
fields.forEach(field) => {
if(field === null || field === '') {
errors = true;
}
});
if (!errors) {
alert('Yay no errors, now you can submit');
}
For an es6 you can use.
const hasNoError = fields.every((field, index, selfArray) => field !== null);
if (!hasNoError) {
alert('yay It works');
};
Have a look at Array.every documentation Array every MDN documentation
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.
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
:) 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.
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...