0

I have a date input on my page, here I have an array with values that is basically the number of days that I want in a month.

dateNumber = [23, 25];
show = true;

if(service == "7305"){
    for(let i = 0; i < dateNumber.length ; i++) {
        if (date.getDate() == dateNumber[i]) {
            show = true;
        } else {
            show = false;
        }
    }
}

Now it looks like this:

dateinput.

The problem is that show is true for 23 and for 25, but it shows only the last element. How can I fix it ?

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • You need to break the loop as soon as the `if` condition evaluates to true. Initialize `show` with `false` and inside the loop, remove the the `else` block. – Yousaf May 19 '21 at 09:22

3 Answers3

1

There are some problems with your code.

I would recommend using the strict mode. 'use strict'; which eliminates some JavaScript silent errors by changing them to throw errors.

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Currently, you have your defined your variables like so.

dateNumber = [23, 25];
show = true;

Although it works but these are leaked globals. When you declare variables without var, let, or const. JS creates that variable in the global scope.

You should always use var, let, or const to define your variables. Read more about it here: https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/

Also use the strict equality operator instead of ==

Read more about it here: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Try this:

'use strict';
const date = new Date();
const dateNumber = [23, 25];
let show = false;

if (service === '7305') {
  for (let i = 0; i < dateNumber.length; i++) {
    if (date.getDate() === dateNumber[i]) {
      show = true;
      break;
    }
  }
}
onlit
  • 728
  • 5
  • 19
0

The problem is that if the date is 23, it will be set to true initially, but the second time through the loop it is not equal to 25, so you will set it to false again!

To fix this simply break out of the loop, or even better, just use:

show = [23, 25].includes(date.getDate());

Turksarama
  • 1,136
  • 6
  • 13
0

You need at least two elements, or have a logo.

dateNumber = [23, 25];
show1 = true;
show2 = true;

then:

if (date.getDate() == dateNumber[i]) {
     show1 = true;
     show2 = true;
 } else {
     show1 = false;
     show2 = false;
 }
Jin Liu
  • 73
  • 6