Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am testing this code:
var thecol = '';
// Note: I know that value.cat = '3'
if (value.cat === '1') {
thecol = 'cat1';
} else if (value.cat === '2') {
thecol = 'cat2';
} else if (value.cat === '3') {
thecol = 'cat3';
} else if (value.cat === '4') {
thecol = 'cat4';
} else if (value.cat === '5') {
thecol = 'cat5';
};
alert(thecol);
The alert is blank for some reason.
Any ideas why.
Are you sure that value.cat is '3' and not 3? You can easily find out by logging typeof value.cat. Since you are using the deep equal it will only return true if both, the value and the type are the same:
'3' === 3 // -> false
'3' == 3 // -> true
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I am still a beginner to JS and I am kinda struggling on how to write multiple ifs in a correct way. For example I wrote something like this:
function calculatespot() {
//Spot 1 to 2 transfer bandage
if (spot1Selected == 1 && spot2Selected == 1) {
if (spot2Free == 1) {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
if (user_item1 == "Bandage") {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", "Bandage")
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = "/static/images/bandage.png"
localStorage.setItem('slot1Type', "")
localStorage.setItem('slot2Type', "Bandage")
}
}
}
This is not a very good way, but I still need all those points to match before executing the code. How could I write something like this in a better and more efficient way without having to nest all those ifs?
You can think about the following things to do:
reverse logic and return
separate logic in multiple functions
That will look like this. Which has the same functionality as your code, but less nested:
function setToSpot2Free() {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
}
function setType2(type) {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", type)
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = `/static/images/${type.toLowerCase()}.png`
}
function calculatespot() {
if (spot1Selected !== 1 || spot2Selected !== 1 || spot2Free !== 1) {
return;
}
setToSpot2Free();
if (user_item == 'Bandage') {
setType2(user_item);
}
}
Obviously there are more things iffy with your code, but you'll get there :)
A very important concept, at least to me, is the DRY principle. Which means, "Don't repeat yourself". If you are noticing that you are doing the same thing twice, with only a small difference in code, you can probably move this logic in its own function and set the "small difference(s)" as parameter(s) of that function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need help with my if conditions.
if(userId && !targetId){
// query logic for userid and no targetid
}
else if (!userId && targetId){
// query logic for targeted and no user id
}
Now how do I write the "else" part? another query logic for when both userid and target id are present.
You may simply tag on another if else:
if (userId && !targetId) {
// query logic for userid and no targetid
}
else if (!userId && targetId) {
// query logic for targeted and no user id
}
else if (userId && targetId) {
// query logic for both true
}
else {
// this defaults to both being false, the other three
// conditions already being handled above
}
you could do
else
{
if(userId && targetId){ }
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to make filter base on input search and select menu at the same time.The filter works for select and search but separately if I try marge I don't have any errors output but the filter doesn't work...
(zemlja.name.toLowerCase().indexOf(search) === 0)
if I remove this from filter, filter will work for select menu but I want to make one filter for search and select
const selectFilter = zemlje.filter((zemlja) => {
if ((zemlja.name.toLowerCase().indexOf(search) === 0) || (select === 'All')
|| (zemlja.region === select)) return true;
});
I would expect the results to contain the search-string and pass the filter-criteria, which is why I would use &&:
const selectFilter = zemlje.filter((zemlja) => {
const searchHit = (zemlja.name.toLowerCase().indexOf(search) === 0);
const filterPass = ((select === 'All') || (zemlja.region === select));
if ( searchHit && filterPass ) return true;
return false;
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
my code is not working at all
I need to solve this quiz
question is write convertToString as function !
this function should convert to string from parameter
ex )
let output = convertToString(120);
console.log(output); // --> '120'
let output2 = convertToString('hello');
console.log(output2); // --> 'hello'
let output3 = convertToString(true);
console.log(output3); // --> 'true'
this is what I wrote
function convertToString(anything) {
if (typeof anything === 'number' && typeof anything === 'boolean') {
let ret = anything.toString()
} else {
return anything;
}
return ret1;
}
convertToString(120);
The easiest way to convert anything is by making + operation with ""
function convertToString(anything) {
return "" + anything
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
console.log(convertToString(null));
console.log(convertToString(undefined));
Zero checks necessary.
function convertToString(val) {
return String(val);
// or return val.toString();
// or return '' + val;
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have this challenge with my code where I want to change this:
function validateLoanAmount(){
var loan_amount = $('[name=loan_amount]');
if(loan_amount.val() == ''){
showError(loan_amount, 'Field can\'t be empty');
return false;
}
if(loan_amount.val() <= 0){
showError(loan_amount, 'Value can\'t equal 0 or less');
return false;
}
}
into this:
function validateLoanTerm(){
var loan_term = $('[name=loan_term]');
isEmpty(loan_term);
isEqualZeroOrLess(loan_term);
}
function isEmpty(element){
if(element.val() == ''){
showError(element, 'Field can\'t be empty');
return false;
}
}
function isEqualZeroOrLess(element){
if(element.val() <= 0){
showError(element, 'Value can\'t equal 0 or less');
return false;
}
}
I tried to put return in front of isEmpty() and isEqualToZeroOrLess(), but then only first function resolved. It looks like a simple function to make shorter (because I have many similar inputs to validate and I want to keep it DRY), but looks like it's more complicated than I initially thought. Any thoughts?
Combine the calls with &&:
function validateLoanTerm(){
var loan_term = $('[name=loan_term]');
return isEmpty(loan_term) && isEqualZeroOrLess(loan_term);
}
But for this to work, the functions need to return true when there's no error.
function isEmpty(element){
if(element.val() == ''){
showError(element, 'Field can\'t be empty');
return false;
}
return true;
}
function isEqualZeroOrLess(element){
if(element.val() <= 0){
showError(element, 'Value can\'t equal 0 or less');
return false;
}
return true;
}