Bar chart not displaying axes and legend values correctly

I am working on a page that uses datatables to retrieve highcharts. Charts for Buttons one and three are fine. The problem I am facing is with Button two – Bar chart. For the chart, I am trying to display the values from column 2022 as Y axis and Percent column as X axis. The legend should also display Y axis columns. What am I missing? Here is my code.

// Function to initialize Highcharts charts
function initializeChart(chartId, chartTitle, chartData, chartType) {
    Highcharts.chart(chartId, {
        chart: {
            type: chartType,
            styledMode: false
        },
        title: {
            text: chartTitle
        },
        colors: ['#1a4480', '#e52207', '#e66f0e', '#ffbe2e', '#fee685', '#538200', '#04c585', '#97d4ea', '#009ec1', '#0076d6', '#adadad', '#8168b3', '#d72d79', '#f2938c'],
        tooltip: {
            pointFormat: '</b> {point.y:.1f}%'
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}%',
                    style: {
                        fontSize: "12px"
                    }
                },
                showInLegend: true
            },
            pie: {
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}%',
                    style: {
                        fontSize: "12px"
                    }
                },
                showInLegend: true
            }
        },
        legend: {
            symbolRadius: 0,
            itemStyle: {
                color: '#000000',
                fontSize: '16px'
            }
        },
        series: [{
            data: chartData
        }]
    });
}

// Function to retrieve chart data from DataTable
function getChartData(table) {
    const data = [];
    table.rows().every(function () {
        const row = this.data();
        data.push({
            name: row[0],
            y: parseFloat(row[1])
        });
    });
    return data;
}

// Check if DataTable and Highcharts are defined before calling the function
if (typeof DataTable !== 'undefined' && typeof Highcharts !== 'undefined') {
    initializeCharts();
}

function initializeCharts() {
    const table1 = new DataTable('#example1', {
        searching: false,
        info: true,
        paging: false,
        sort: false
    });
    const table2 = new DataTable('#example', {
        searching: false,
        info: true,
        paging: false,
        sort: false
    });

    const chartData1 = getChartData(table1);
    const chartData2 = getChartData(table2);

    initializeChart('demo-output', 'FY 2023', chartData1, 'pie');
    initializeChart('demo-output2', 'FY 2022', chartData2, 'bar');

    var categories = [];
    var allSeriesData = [];

    var table = $("#example2").DataTable({
        searching: false,
        responsive: true,
        lengthChange: false,
        ordering: false,
        info: false,
        paging: false,
        initComplete: function (settings, json) {
            let api = new $.fn.dataTable.Api(settings);

            var headers = api.columns().header().toArray();
            headers.forEach(function (heading, index) {
                if (index > 0 && index < headers.length) {
                    categories.push($(heading).html());
                }
            });

            let rows = api.rows().data().toArray();
            rows.forEach(function (row) {
                group = {
                    name: '',
                    data: []
                };
                row.forEach(function (cell, idx) {
                    if (idx == 0) {
                        group.name = cell;
                    } else if (idx < row.length) {
                        group.data.push(parseFloat(cell.replace(/,/g, '')));
                    }
                });
                allSeriesData.push(group);
            });
        }
    });

    Highcharts.setOptions({
        lang: {
            thousandsSep: ','
        }
    });

    var myChart = Highcharts.chart("chart-A", {
        chart: {
            type: "column",
            borderColor: 'lightgray',
            borderWidth: 1,
            marginTop: 50
        },
        tooltip: {
            headerFormat: '{point.key}<br/>',
            pointFormat: '{series.name}: <b>{point.y:.1f}%</b>'
        },
        legend: {
            symbolRadius: 0,
            itemStyle: {
                color: '#000000',
                fontSize: '16px'
            }
        },
        colors: ['#003489', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5'],
        credits: {
            enabled: false
        },
        title: {
            text: "Trends"
        },
        xAxis: {
            categories: categories,
            labels: {
                style: {
                    fontWeight: '600',
                    fontSize: '16px',
                    color: '#000000'
                }
            }
        },
        yAxis: {
            title: false,
            tickInterval: 10,
            max: 60,
            labels: {
                formatter: function () {
                    return Highcharts.numberFormat(this.value, 0);
                },
                style: {
                    fontWeight: '600',
                    fontSize: '16px',
                    color: '#000000'
                }
            }
        },
        series: allSeriesData
    });

    $('.usa-button').on('click', function () {
        var buttonId = $(this).attr('id');

        if (buttonId === 'previous') {
            $('#chart2').show();
            $('#chart1').hide();
            $('#chart3').hide();
        } else if (buttonId === 'trend') {
            $('#chart2').hide();
            $('#chart1').hide();
            $('#chart3').show();
        } else {
            $('#chart2').hide();
            $('#chart1').show();
            $('#chart3').hide();
        }

        $('.usa-button').removeClass('active');
        $(this).addClass('active');
    });

    $('#current').addClass('active');
}
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <link href="https://nightly.datatables.net/css/dataTables.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/dataTables.js"></script>

 <script src="https://code.highcharts.com/highcharts.js"></script>

  </head>
  <body>




<div class="ar-controls grid-row tablet:flex-justify-start">
<div class="tablet:grid-col-auto margin-bottom-205"><button id="current" class="usa-button usa-button--outline" title="Select to see related information below">one</button> <button id="previous" class="usa-button usa-button--outline" title="Select to see related information below">two</button> <button id="trend" class="usa-button usa-button--outline" title="Select to see related information below">three</button></div>
</div>

<div id="chart1">
<div id="demo-output" class="chart-display" style=" margin-bottom: 2em; height: 500px; border: solid 1px lightgray;"></div>

<table id="example1" class="display" style=" width: 100%;"><thead>
<tr>
<th scope="col">2023</th>
<th scope="col">Percent</th>
</tr>

</thead>
<tr>
<td scope="row">ABC</td>
<td>45.9%</td>
</tr>

<tr>
<td scope="row">DEF</td>
<td>22.0%</td>
</tr>

<tr>
<td scope="row">GHI</td>
<td>13.6%</td>
</tr>

</table>
</div>

<div id="chart2" style=" display: none;">
<div id="demo-output2" class="chart-display2" style=" margin-bottom: 2em; height: 680px; border: solid 1px lightgray;"></div>

<table id="example" class="display" style=" width: 100%;"><thead>
<tr>
<th scope="col">2022</th>
<th scope="col">Percent</th>
</tr>

</thead>
<tr>
<td>123</td>
<td>51.90%</td>
</tr>

<tr>
<td>456</td>
<td>18.60%</td>
</tr>

</table>
</div>

<div id="chart3" style=" display: none;">
<div id="chart-A" style=" width: 100%; height: 500px;"></div>

<table class="row-border stripe no-footer cell-border padding-top-5" id="example2" style=" width: 100%;"><thead>
<tr>
<th>Year</th>
<th>column1</th>
<th>column2</th>
<th>column3</th>

</tr>

</thead>
<tr>
<td scope="row" style=" text-align: left; white-space: nowrap;">FY19</td>
<td style=" text-align: left;">42.7%</td>
<td style=" text-align: left;">17.3%</td>
<td style=" text-align: left;">9.5%</td>

</tr>

<tr>
<td scope="row" style=" text-align: left;">FY20</td>
<td style=" text-align: left;">49.5%</td>
<td style=" text-align: left;">16.3%</td>
<td style=" text-align: left;">3.4%</td>

</tr>


</table>
</div>
</div>

Chart.js is not visible, but does show up on HTML

I am creating a dashboard, on this dashboard i make a call to some charts using htmx, but the chart is not rendering properly, when i inspect the element i can see the script, canvas and code but not the visual of the graph. I am using flask and python and this is my code pre the dashboard that calls the chart:

<div>
    <div class="toolbox">
        <h1>Budget</h1>
        <div>
            <div hx-get="/auth/budget/expense_form" hx-swap="innerHTML" hx-trigger="load once" id="expense_form_field">
            </div>
            <div hx-get="/auth/budget/dashboard" hx-swap="outerHTML" id="dashboard" hx-target="#dashboard"
                hx-trigger="load once">
            </div>
        </div>
    </div> </div> </div>

And this is what html is returned:

<div>
    <canvas id="myChart"></canvas>
</div>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const ctx = document.getElementById('myChart');

    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });</script>

I have looked to the following similar questions, but i have not found any of their fixes useful: enter link description here, enter link description here,enter link description here

When i check the console errors i am noticing this:

Uncaught ReferenceError: Chart is not defined
    at <anonymous>:4:19
    at At ([email protected]:1:22924)
    at Nt ([email protected]:1:23051)
    at [email protected]:1:10309
    at [email protected]:1:44741
    at oe ([email protected]:1:4604)
    at s ([email protected]:1:44716)

my thinking is that HTMX is affecting the script? Also when i inspect the chart element in browser it has an htmx class tag, could this be interfering with the script?

<script class="htmx-settling">
    const ctx = document.getElementById('myChart');

    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });</script>

How can I remove one of the clicks from hide/show?

I’m trying to show/hide more info about names on click, but don’t know how to make it work of a single click.

I’m creating a div with JS like so:

const newDiv = document.createElement("div");
newDiv.className = "game-info";
newDiv.innerHTML = `
<p onclick="toggler()";>${game.Name}</p>
<div class="info">
<img src="${game.Thumbnail}">
<p>${game.Description}</p>
</div>
`;
document.body.appendChild(newDiv);

The toggler function is written like this:

function toggler(){
    $('div.game-info').click(function(e){
        $(this).children('.info').toggle();
    });
}

It kinda works, but it takes one or more clicks to view the additional info. I know the problem is due to multiple onclick calls, but don’t know how to make it with a single click. I tried using jQuery without the toggler function, but then it opens info on all the names and not just the one which was clicked. So if someone could either tell me how to get rid of that secondary onclick or how to properly target the info which I clicked in the innerHTML section that’d be great!

How to parse String Data to JSON format or extract name value pair

I am developing a Web Page which receives below data over socket:

{
        "version":      1,
        "timestamp":    "1990-01-01T02:10:45.265Z",
        "points":       {
                        "motor_voltage": {
                                        "present_value":        0
                                },
                        "motor_current": {
                                        "present_value":        0
                                },
                        "speed_rpm":     {
                                        "present_value":        0
                                },
                        "running_hours": {
                                        "present_value":        1
                                },
                        "drive_temperature":     {
                                        "present_value":        0
                                },
                        "analog_input_2":        {
                                        "present_value":        0
                                },
                        "status_word":   {
                                        "present_value":        "600hex"
                                },
                        "digital_input": {
                                        "present_value":        64
                                },
                        "digital_output":        {
                                        "present_value":        0
                                }
                }
                                        "booldigital_output":        {
                                        "present_value":        0
                                }
}

I have tried a log how use JavaScript to parse this string and extract like below

motor_voltage: { present_value: 0 }

And all others – like we get each key value present_values in an array? If I call JSON.parse method – it throws an error that object is not in JSON format.

How can I extract the data from above string as per the values required?

PDF Editor to replace certain Elements (SAP / JavaScript)

I got the task to create an SAP UI5 Fiori application where you can upload a pdf file and where the application automatically blacks out personal information like the name or the phone number. Or if this is not working, at least black it out by yourself through an editor function. Therefore i need to be able to have access to the text from the pdf file.

I tried to solve this via base64 encoding and i was hoping that i can simply replace the base64 string of for example “John Smith” with the encoded string of “****”. But these strings are not found in the pdf or img encoded base64 string. I could extract the text from the pdf file and replace it there but the task says that the layout and design of the given pdf file should stay the same.

So since the base64 attempt doesnt seem to work i need to build my own pdf editor. The given PDF viewer of SAP lets me view the pdf but not edit it in any way. The same seems to be the case for pdf.js since there are no tutorials on how to build an actual editor with it.

The only tutorials that i could find were some short explanations about the code, but the code itselfs lies behind a $100 paywall..

So what would be the best way to solve this task and build pdf editor?

If things are unclear or need further explanation, let me know!

Updating nested cache in Apollo GraphQL

I am fetching a list of documents from the backend using this query:

gql`
  query GetUserDocuments($userId: Int!, $filters: DocumentFilter) {
    user(userId: $userId) {
      id
      documents(filters: $filters) {
        id
        name
      }
    }
  }
`;

The following object is saved in the Apollo cache

User:{"userId":123}

which has 2 nested collections defined inside

documents({"filter":{"archived": false}})
documents({"filter":{"archived": true}})

the apollo cache looks something like this

User:{"userId":123} {
  __typename: "User",
  userId: 123,
  documents({"filter":{"archived": false}}): []
  documents({"filter":{"archived": true}}): []
}

On the frontend, I would like to handle this cache so that when I archive a given document, I remove it from the collection documents({"filter":{"archived": false}}) and I want to put it in the collection documents({"filter":{"archived": true}}). Similarly, when I unarchive a document, I remove it from the archived list and add it to the unarchived list. Is it possible to do this using a cache update? Or do I have to refetch the data, which I would like to avoid?

I tried using cache.modify, however I am getting 2 collections at the same time:

cache.modify({
  id: cache.identify({ __typename: "User", userId }),
  fields: {
    documents: (documents) => {
      return documents;
    },
  },
});

Open rowContextMenu with Button click on Tabulator Table

I want to have a button at the end of my Table where i can Click and open the rowContextMenu below the Button.

But i also want it to pop up when I rightclick anywhere on the row.

I already tried a few things

var menuButtonFormatter = (cell: any) => {
var menuBtn = document.createElement('button');
          menuBtn.type = 'button';
          menuBtn.innerHTML = '<span class="material-icons" style="color: #707070">more_horiz</span>';
          menuBtn.classList.add('menu-button');
          menuBtn.addEventListener('click', (event) => {
            event.stopImmediatePropagation();
            const myEvent: any = new Event('row-contextmenu');
            myEvent.pageX = event.pageX;
            myEvent.pageY = event.pageY;
            cell.getRow().getElement().dispatchEvent(myEvent);
          });

buttonHolder.appendChild(menuBtn);
          return buttonHolder;

        }

This is the Button

And my Column looks like this:

{
        title: this.$t('actions'),
        field: 'actions',
        // formatterParams: poParams,
        formatter:menuButtonFormatter,
        headerSort: false,
        width: 110,
        frozen: true,
}

I tried many different Things but nothing would work.

I also tried const myEvent: any = new Event('contextmenu'); as the button Event but it also did nothing. Also nothing showed up in the Console

Select the Enum dynamically

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. At runtime, the country name is decided (could be one of INDIA or USA or AUSTRALIA). Is there a way I can pick the right enum based on the country name at runtime. For example, if the country name is USA , I want to pick Country_USA enum.

enum Country_INDIA {

  INTREST_RATE = '10%',
  MIN_INVESTMENT_DURATION = "5YRS"

};

enum Country_USA {

  INTREST_RATE = '3%',
  MIN_INVESTMENT_DURATION = "3YRS"
};

enum Country_AUSTRALIA {

  INTREST_RATE = '5%',
  MIN_INVESTMENT_DURATION = "2YRS"
};

let country_enum = "Country_"+"USA" 

console.log(country_enum.INTREST_RATE); // get the interst rate from 'Country_USA' enum

How to make SwiperJs vertical mode, swipes BTT (from Bottom to Top)?

I’m using swiperJs on a React project to to escalate from a number to another. but the number is always raising up (like a stats of total gaining). So I wanna make it scroll/swipe from bottom to top but it works upside down.

they have a prop there: ‘rtl’, which is the solution but for the horizontal swiper.
https://swiperjs.com/demos#rtl
is there any props like this or another way to change the direction of the swiper vertically?
the red arrow is the current behavior , the green arrow is the wanted behavior

How to make the score display the highest at the top [closed]

I want to sort the score from high to low. what code do I need to add? I’m just starting to learn about JavaScript and I got this source from others

//Renders high scores stored in local storage
function renderHighScores() {
    // Clear content
    scoresEl.innerHTML = "";
    show(highScoresEl);
    highScores = JSON.parse(localStorage.getItem("scores"));
    for (let i = 0; i < highScores.length; i++) {
        let scoreItem = document.createElement("div");
        scoreItem.className += "row mb-3 p-2";
        console.log(scoreItem)
        scoreItem.setAttribute("style", "background-color:#fdf8f8;");
        scoreItem.textContent = `${(i + 1)}. ${highScores[i].username} - ${highScores[i].userScore}`;
        scoresEl.appendChild(scoreItem);
    }
}

Can someone help me to figure out how to solve this?

js net::ERR_ABORTED 404 (Not Found)

I use Allure report in Azure DevOps, and hosted this report in Azure Storage Account. I want share this report in my confluence page. For implement this i use macro “HTML include”. But when i try to share my allure report i have error “js net::ERR_ABORTED 404 (Not Found)”

My structure in azure storage account like this:
enter image description here

My index.html like this:

<!DOCTYPE html>
<html dir="ltr">
<head>
    <meta charset="utf-8">
    <title>Allure Report</title>
    <link rel="favicon" href="favicon.ico?v=2">
    <link rel="stylesheet" type="text/css" href="styles.css">
        <link rel="stylesheet" href="plugins/screen-diff/styles.css">
</head>
<body>
<div id="alert"></div>
<div id="content">
    <span class="spinner">
        <span class="spinner__circle"></span>
    </span>
</div>
<div id="popup"></div>
<script src="app.js"></script>
    <script src="plugins/behaviors/index.js"></script>
    <script src="plugins/packages/index.js"></script>
    <script src="plugins/screen-diff/index.js"></script>
</body>
</html>

I investigated my issue, and if i added an absolute path to “script src” for example “<script src=”https://”<my_allure_report_url>”/$web/$(Build.BuildNumber)/app.js”>”
I have other errors something like this:
https://”<confluence___url>”/pages/widgets/executors.json 404 (Not Found)” etc.
enter image description here

First off all i dont understand why if i try use HTML include confluence rewrite path to this file ?
Furthermore what i need to do for resolve my problem with share allure report to confluence page ? Maybe i need modify index.html, or configure Azure CND, or install some custom plagin to confluence server ?

Any ideas ? Please helm me.

P.S. I need to use Azure storage account for my static allure report. Because only in storage account i can store a lot of report. If i right understand in azure storage static web site i cant configure web.config and use it. In Allure documentation they recommended use this solution:

“Please note If you use Azure Website or IIS in general some file types used by Allure are not enabled by default. Please, add mimetypes as shown below to your web.config in order to enable support of .json and .woff file types.”

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
     </staticContent>
    </system.webServer>
</configuration> 

But it not work for Azure storage account. It work only for Azure web app.

How to make the scroll bar show how much you scrolled for the whole page

I have some code. It only shows how much you scrolled in the navbar, not how much you scrolled in the actual webpage.

I think its the problem with the javascript code. When I tried changing it to document instead of nav, errors came on the console.

const nav = document.querySelector('nav');
    const progress = () => {
        let scroll = nav.scrollTop;
        let height = nav.scrollHeight - nav.clientHeight;
        let scrollProgress = (scroll / height) * 100;
        document.getElementById("scroll-progress").style.width = scrollProgress + "%";
    }

    nav.addEventListener('scroll', progress);
 nav {
        justify-content: center;
        width: 100%;
        font-weight: 900;
        color: white;
        background-color: black;
        z-index: 50;
        height: 100px;
        overflow: auto;
    }

    .nav-items {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .nav-sec, .section-navigate {
        display: flex;
        padding: 0px;
        list-style-type: none;
        justify-content: center;
        align-items: center;
        margin: 0px;
    }

    .navigate {
        cursor: pointer;
    }

    .section-navigate {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0px;
        flex-wrap: wrap;
    }

    .link {
        width: 300px;
        height: 60px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

    .scroll {
        width: 100%;
        height: 4px;
        background-color: lightgray;
    }

    #scroll-progress {
        width: 0%;
        height: 4px;
        background-color: green;
    }
Hello, I have edited your code to make it so it will show the scroll of the navigation bar. If you need anything, please ask me. DONT FORGET TO MARK THIS ANSWER CORRECT!



    <header>
            <section class="close">
                <div class="sec-contain">
                    <h1 class="sec-head">
                        FIRST THINGS FIRST
                    </h1>
                    <p class="sec-text">
                        Lorem ipsum 
                    </p>
                    <p class="sec-text">
                        Vivamus dictum aliquam posuere. 
                    </p>
                    <p class="sec-text">
                        Vestibulum iaculis ligula 
                    </p>
                </div>
            </section>
        </header>
        <nav class="nav" id="navigation">
                <div class="nav-items">
                    <ul class="nav-sec">
                        <li class="current-sec">
                            <p class="current" id="text">
                               First Thing's First 
                            </p>
                        </li>
                        <li class="navigate">
                            <ul id="btn" class="nav-list">Take Me To</ul>
                        </li>
                    </ul>
                </div>
                <div class="modal" id="jump-links">
                    <div class="close" id="close-btn">&times;</div>
                    <ul class="section-navigate">
                        <li class="link close"><a href="#one">First Things Second</a></li>
                        <li class="link close"><a href="#two">First Second Third Things Third</a></li>
                        <li class="link close"><a href="#three">Seven</a></li>
                        <li class="link close"><a href="#four">Last Things First</a></li>
                    </ul>
                </div>
                
            </nav>
            <div class="scroll">
                    <div class="scroll-bar" id="scroll-progress"></div>
                </div>
        <main>
            <div class="anchor" id="one"></div>
            <section class="close" id="one-txt">
                <div class="sec-contain">
                    <h1 class="sec-head">
                        FIRST THINGS SECOND
                    </h1>
                    <p class="sec-text">
                        Lorem ipsum dolor sit amet
                    </p>
                    <p class="sec-text">
                        Lorem ipsum dolor si
                    </p>
                </div>
                <div class="anchor" id="two"></div>
            </section>
            <section class="close">
                <div class="sec-contain">
                    <h1 class="sec-head">
                        FIRST SECOND THIRD THINGS THIRD
                    </h1>
                    <p class="sec-text">
                        Lorem ipsum dolor sit amet,
                    </p>
                    <p class="sec-text">
                        Ut imperdiet tortor eget
                    </p>
                    <p class="sec-text">
                        Donec finibus augue
                    </p>
                    <p class="sec-text">
                        Donec in suscipit 
                    </p>
                </div>
                <div class="anchor" id="three"></div>
            </section>
            <section class="close">
                <div class="sec-contain">
                    <h1 class="sec-head">
                        SEVEN
                    </h1>
                    <p class="sec-text">
                        sevensevensevensevensevensevenseven
                    </p>
                </div>
                <div class="anchor" id="four"></div>
            </section>
            <section class="close">
                <div class="sec-contain">
                    <h1 class="sec-head">
                        LAST THINGS FIRST
                    </h1>
                    <p class="sec-text">
                        Lorem ipsum dolor sit amet
                    </p>
                    <p class="sec-text">
                        Duis sed felis ac iis feugiat elit. Duis tempus feugiat risus ut placerat. Cras sit amet ligula urna.
                    </p>
                    <p class="sec-text">
                        Cras eu mattis odio. 
                    </p>
                    <p class="sec-text">
                        Ut cursus sit 
                    </p>
                </div>
            </section>
        </main>
        <section id="end-stick" class="close">
            <div class="sec-contain">
                <h1 class="sec-head">
                    SECOND THINGS LAST
                </h1>
                <p class="sec-text">
                    Lorem ipsum dolor sit amet,
                </p>
                <p class="sec-text">
                    Class aptent taciti socios
                </p>
                <p class="sec-text">
                    Praesent nec sollicitudin nibh
                </p>
            </div>
        </section>

Please help me fix the problem. THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG . IM DOING THIS BECAUSE STACKOVERFLOW SAID THAT MY POST IS MOSTLY CODE AND I SHOULD ADD SOME DETAILS LOL

Check isValidDate in JavaScript

I’m currently using a JavaScript function to check if a given string represents a valid date. However, I’ve encountered a problem where certain non-date strings, like “SA-0001” or simple numbers inside strings like “1”, are erroneously being identified as valid dates.

function isValidDate(val) {
    if (typeof val === 'number') {
        return false;
    }
    const str = new Date(val);
    if (str != 'Invalid Date') {
        return true;
    } else {
        return false;
    }
}

In the incoming string, the format for valid date string varies and is not fixed, such as ‘yyyy-mm-dd’, and I aim to avoid restricting the backend to a specific format. How can I accurately determine if a given value represents a valid date without imposing a fixed format constraint?

Ex.

  • Input: ‘1999-01-01’ Expected result: true
  • Input: ’01-01-1999′ Expected result: true
  • Input: ’01-1999-01′ Expected result: true
  • Input: ‘Fri Mar 15 2024 18:19:30’ Expected result: true
  • Input: ’01-01′ Expected result: false
  • Input: ’01’ Expected result: false
  • Input: ‘sa-0001’ Expected result: false