js get index from array

I have this code that I believe dynamically

<select name="list[]"></select>
<input name="field[]">

<select name="list[]"></select>
<input name="field[]">


<select name="list[]"></select>
<input name="field[]">

I would like the onchange of a select to be returned to me the index to dynamically fill the relative input

How to alert user before leaving webpage and run ajax function if user presses “ok”?

I have this function that is supposed to ask the user if they are sure that they want to leave or refresh the website and if they say yes and leave the ajax function is executed. My problem is if the ajax function is alone the user is given no warning but if anything else is in the code the ajax function doesn’t work.

<script type="text/javascript">
            window.onbeforeunload = function () {
                return "";
                $.ajax({url: "checkout.php", type : 'post', data : { page_left: 1}});
            }
       </script>

GoJS: Prevent specific region from being occupied by nodes in a ForceDirectedLayout

I’d like to prevent a specific coordinate area reserved for a legend in my GoJS diagram which is using a ForceDirectedLayout for node layouts. However, the legend shape doesn’t affect the layout of nodes when applied as a Part, and using a placeholder Node unfortunately doesn’t allow placement based on document coordinates.

How can you create a region in a ForceDirectedLayout which affects nodes as they’re being calculated but in turn either isn’t a node or is a fixed node position without any links?

Ideally it’d be possible to define a specific Rect in the diagram which isn’t accessible for nodes, but the closest I could find is the total bounding box via boundsComputation which would just narrow the area and not allow for cutting a specific region out.

Here’s a specific illustration of the challenge, where the legend will generally overlapping with node content without some force to repel the nodes:

enter image description here

has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value

full erorr

Access to XMLHttpRequest at 'https:/domain/errors/403/' (redirected from 'http://domain/includes/action.php') from origin 'domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://domain' that is not equal to the supplied origin.

the code should to search without refresh so in localhost all work right but when i go to server i got this erorr in console

here my php where i got respond to my main page

my php code

<?php
include 'db.php';
if (isset($_POST['search'])) {
$Name = $_POST['search'];
$Query = "SELECT * FROM items WHERE name LIKE '%$Name%' OR namea LIKE '%$Name%' LIMIT 6";
$q2 = "SELECT * FROM items WHERE namea LIKE '%$Name%' LIMIT 6";
$ExecQuery = mysqli_query($con, $Query);
$ExecQuery2 = mysqli_query($con, $q2);
if ($ExecQuery) {
    $go = $ExecQuery;
} else {
    $go = $ExecQuery2;
}
echo '<ul class="cards">';
while ($row = mysqli_fetch_array($go)) {
    $name = $row['name'];
    $p = $row['price'];
    $d = $row['descrip'];
    $m = $row['img'];
    echo '
    <li class="cards__item">
    <div class="card">
        <img src="pimg/' . $m . '" class="card__image">
        <div class="card__content">
            <div class="card__title">name: ' . $name . '</div>
            <div class="card__title">price: ' . $p . ' $</div>
            <p class="card__text">' . $d . '</p>
            
        </div>
    </div>
    </li>';
}

}
here my js code to send the data to search.php and got the respond

ajax code

function fill(Value) {
$('#search').val(Value);
$('#display').hide();
}
$(document).ready(function () {
$("#search").keyup(function () {
    var name = $('#search').val();
    if (name != "") {
        $.ajax({
            type: "POST",
            url: "includes/search.php",
            data: {
                search: name
            },
            success: function (html) {
                $("#display").html(html).show();
            }
        });
    }
});
});

Validate a URL link

I simply want to validate that a link to help text is a valid link when entering the link in a CRUD operation. When I use fetch it fails if the link is to an invalid site, however, not if it is to a bad page on a site (404). The response from the fetch is the same to both a valid page and a non-vaid page, yet google Chrome seems to know.

DevTools image

  const g_log1 = true
  if (g_log1) console.log('URL ', url)
  try {
    const urlOptions = {
      method: 'HEAD',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' }
    }
    fetch(url, urlOptions)
      .then(response => {
        if (g_log1) console.log(url, '--1--', response)
        return true
      })
      .catch(error => {
        if (g_log1) console.log(url, '--2--', error)
        return false
      })
  } catch (error) {
    if (g_log1) console.log(url, '--3--', error)
    return false
  }
}

export default apiCheckURL

Is there anything simmilar to res.redirect but in normal JavaScript?

I’m trying to make a re-director with plain JS (https://example.com/?ABCD -> https://example.org/t/ABCD), it works fine but when I use it with image urls, the image won’t be shown when put into Discord, Twitter, etc. Then I tried to use Express’ res.redirect and it did work.
Can you do anything simmilar to that but in normal JavaScript? I’ve tried this:

let url = `https://example.org/t/${window.location.search.slice(1)}`;
let el = document.createElement("meta")
el.setAttribute("http-equiv", "refresh");
equiv.setAttribute("content", `0;url=${url}`);
document.head.appendChild(el;

Which adds a <meta> tag to the head section, but it is still not working.

JSF/PrimeFaces – Access remoteCommand’s from DOM Listener

I am having an issue using remoteCommands with a JavaScript DOM Listener. I have a listener defined like so on a JSF page:

<script>
    $(document).keydown(function(e) {
        onEnter();
    }
</script>

And a remote command defined like so:

<p:remoteCommand name="onEnter" action="{primeView.onEnter(iter)}" style="display: none;"/>

For what its worth, the remoteCommand is within a p:dataTable with var=iter. I’ve also tried adding process="@form" and immediate="true", with no change.

When pressing any key on the page, the JavaScript listener is called, but the following error is output:

Uncaught ReferenceError: onEnter is not defined

I’m assuming this is because DOM listeners have a different scope that normal native JavaScript. So, how can I access the remoteCommand from within a listener?

Code from pencode.io not working on GitHub Pages abd VS Code

So i have a code from codepen.io, here’s the link – https://codepen.io/akshzyx/pen/JjOqbRG

The countdown works perfectly well on codepen.io but when i try to run code on GitHub Pages or VS Code the countdown number doesn’t work or show up. Have attached the images at last.

Here’s the code

HTML

    <main>
    <div class="intro">
        <h1 class="intro__headline">The Unix Epochalypse</h1>
        <p class="intro__subheadline">Happening In</p>
        <div class="cd">
            <div class="cd__unit-group">
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Year(s)</div>
                </div>
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Month(s)</div>
                </div>
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Day(s)</div>
                </div>
            </div>
            <div class="cd__unit-group">
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Hour(s)</div>
                </div>
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Minute(s)</div>
                </div>
                <div class="cd__unit">
                    <div class="cd__digits">
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                        <div class="cd__digit" data-col>
                            <div data-pos="next">-</div>
                            <div data-pos="prev">-</div>
                        </div>
                    </div>
                    <div class="cd__unit-label">Second(s)</div>
                </div>
            </div>
            <div class="cd__progress">
                <span class="cd__unit-label">Seconds Since Unix Epoch</span><br>
                <strong data-progress>-</strong>
            </div>
        </div>
        <button id="info-btn" class="btn" type="button">
            <span class="btn__text">?</span>
        </button>
    </div>
    <div id="info" class="content">
        <div class="content__wrap">
            <h2>What’s the Unix Epochalypse?</h2>
            <p>The Unix Epochalypse (or the <a href="https://en.wikipedia.org/wiki/Year_2038_problem" target="_blank" ref="noopener noreferrer">Year 2038 problem</a>) is the day clocks on a number of systems will flip from <strong><time datetime="2038-01-19 03:14:08">January 19, 2038 3:14:08 AM UTC</time></strong> to <strong><time datetime="1901-12-13 20:45:52">December 13, 1901 8:45:52 PM UTC</time></strong>. This is because of the use of a 32-bit signed integer for the current seconds since midnight UTC on <time datetime="1970-01-01 00:00:00">January 1, 1970</time>, the Unix epoch. Values only from -2,147,483,648 to 2,147,483,647 are stored. When finally reaching the limit, it’ll be the seconds before the epoch starting at the lowest supported integer.</p>
            <p>If you have yet to make the complete shift to 64-bit, expect some strange things to happen later. The age of 32-bit is over. The time of 64-bit has come!</p>
        </div>
    </div>
</main>
<footer>
    Made by <a href="https://github.com/akshzyx" target="_blank">@akshzyx</a>
</footer>

CSS

* {
    border: 0;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
:root {
    --hue: 223;
    --bg1: hsl(var(--hue),10%,90%);
    --bg2: hsl(var(--hue),10%,100%);
    --fg1: hsl(var(--hue),10%,10%);
    --fg2: hsl(var(--hue),10%,30%);
    --primary1: hsl(var(--hue),90%,45%);
    --primary2: hsl(var(--hue),90%,55%);
    --primary3: hsl(var(--hue),90%,65%);
    --primary4: hsl(var(--hue),90%,75%);
    --primary5: hsl(var(--hue),90%,85%);
    font-size: calc(16px + (24 - 16) * (100vw - 320px) / (1280 - 320));
}
body, button {
    font: 1em/1.5 Hind, sans-serif;
}
body {
    background: var(--bg1);
    color: var(--fg1);
}
a {
    color: var(--primary2);
}
a:not(:hover) {
    text-decoration: none;
}
a:active {
    color: var(--primary1);
}
a:visited {
    color: var(--primary3);
}
h1 {
    font-size: 2em;
    margin: 0 0 1.5rem;
    text-align: center;
}
h2 {
    font-size: 1.5em;
    line-height: 1;
    margin: 0 0 0.75rem;
    padding-top: 0.75rem;
}
p {
    margin: 0 0 1.5em;
}
footer {
    font-size: 0.75em;
    padding: 1.5em;
    text-align: center;
}
.intro__headline,
.intro__subheadline,
.cd__digits,
.cd__unit-label,
.cd__progress {
    font-family: Inconsolata, monospace;
}
.intro {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100vh;
    min-height: 19.5em;
    padding: 1.5em;
}
.intro__headline {
    font-size: 3em;
    line-height: 1;
    text-transform: uppercase;
}
.intro__subheadline {
    color: var(--fg2);
    text-align: center;
}
.cd,
.cd__unit-group,
.cd__digits {
    display: flex;
    justify-content: center;
}
.cd {
    flex-wrap: wrap;
    text-align: center;
}
.cd__unit-group {
    margin-bottom: 1.5em;
}
.cd__unit {
    font-size: 3.75em;
    line-height: 1;
    margin: 0 0.75rem;
    width: 2ch;
}
.cd__digits,
.cd__digit {
    position: relative;
}
.cd__digits {
    box-shadow:
        0 0.1em 0.05em var(--bg1) inset,
        0 -0.1em 0.05em var(--bg1) inset;
    font-weight: bold;
    height: 3.75rem;
    margin-bottom: 0.5rem;
    overflow: hidden;
}
.cd__digit {
    width: 1ch;
    z-index: -1;
}
.cd__digit--roll-in {
    animation: rollIn 0.5s ease-in-out;
}
.cd__next-digit-fade {
    animation: fade 0.5s ease-in-out;
}
.cd__prev-digit-fade {
    animation: fade 0.5s ease-in-out reverse;
}
.cd__unit-label {
    color: var(--fg2);
    font-size: 0.75rem;
    line-height: 1;
}
.cd__progress {
    width: 100%;
}
.btn {
    background: var(--primary2);
    border-radius: 50%;
    color: #fff;
    position: fixed;
    right: 1.5em;
    bottom: 1.5em;
    text-align: center;
    width: 2.25em;
    height: 2.25em;
    transition: background-color 0.15s linear;
    -webkit-appearance: none;
    appearance: none;
}
.btn:focus,
.btn:hover {
    background-color: var(--primary1);
}
.btn__text {
    display: block;
    font-size: 1.5em;
    font-weight: bold;
    height: 100%;
    padding-top: 0.125rem;
}
.content {
    background: var(--bg2);
}
.content__wrap {
    margin: auto;
    padding: 3em 1.5em 1.5em;
    max-width: 32em;
}

/* Dark theme */
@media (prefers-color-scheme: dark) {
    :root {
        --bg1: hsl(var(--hue),10%,10%);
        --bg2: hsl(var(--hue),10%,20%);
        --fg1: hsl(var(--hue),10%,90%);
        --fg2: hsl(var(--hue),10%,70%);
    }
    a {
        color: var(--primary3);
    }
    a:active {
        color: var(--primary2);
    }
    a:visited {
        color: var(--primary4);
    }
}

/* Animations */
@keyframes rollIn {
    from { transform: translateY(-100%); }
    to { transform: translateY(0); }
}
@keyframes fade {
    from { opacity: 0; }
    to { opacity: 1; }
}

JS

window.addEventListener("DOMContentLoaded",() => {
    const uec = new UnixEpochalypseCountdown(".cd");
    const infoBtn = document.getElementById("info-btn");

    if (infoBtn)
        infoBtn.addEventListener("click",jumpToHelp);
});

function jumpToHelp() {
    const info = document.getElementById("info");

    if (info) {
        window.scrollTo({
            top: info.offsetTop,
            left: 0,
            behavior: "smooth"
        });
    }
}

class UnixEpochalypseCountdown {
    constructor(qs) {
        this.el = document.querySelector(qs);
        this.time = [];
        this.animTimeout = null;
        this.updateTimeout = null;
        this.update();
    }
    getProgressInSeconds() {
        if (typeof moment === "function") {
            const now = moment();
            const ms = Math.ceil(now.valueOf() / 1e3);

            return ms >> 0;
        } else {
            return 0;
        }
    }
    getTimeLeft() {
        let timeLeft = {
            y: 0,
            mo: 0,
            d: 0,
            h: 0,
            m: 0,
            s: 0
        };

        if (typeof moment === "function") {
            const later = moment((2**31 - 1) * 1e3);
            const now = moment();
            const diff = moment.duration(later.diff(now));

            if (diff.valueOf() >= 0) {
                timeLeft.y += diff.years();
                timeLeft.mo += diff.months();
                timeLeft.d += diff.days();
                timeLeft.h += diff.hours();
                timeLeft.m += diff.minutes();
                timeLeft.s += diff.seconds();
            }
        }

        return timeLeft;
    }
    clearAnimations() {
        if (this.el) {
            const colAnimsToClear = this.el.querySelectorAll("[data-col]");

            Array.from(colAnimsToClear).forEach(a => {
                a.classList.remove("cd__digit--roll-in");
            });

            const posAnimsToClear = this.el.querySelectorAll("[data-pos]");

            Array.from(posAnimsToClear).forEach(a => {
                a.classList.remove("cd__next-digit-fade","cd__prev-digit-fade");
            });
        }
    }
    update(doAnimations = false) {
        // start with all dashes
        if (!this.time.length) {
            let digitCount = 12;

            while (digitCount--)
                this.time.push("-");
        }
        // update data
        const display = this.getTimeLeft();
        const displayDigits = [];

        for (let v in display) {
            const digits = `${display[v]}`.split("");
            // add zero to single digits
            if (digits.length < 2)
                digits.unshift("0");

            displayDigits.push(...digits);
        }
        // update display
        const cols = this.el.querySelectorAll("[data-col]");

        if (cols) {
            Array.from(cols).forEach((c,i) => {
                const digit = displayDigits[i];

                if (digit !== this.time[i]) {
                    const next = c.querySelector(`[data-pos="next"]`);
                    const prev = c.querySelector(`[data-pos="prev"]`);

                    if (doAnimations === true) {
                        c.classList.add("cd__digit--roll-in");
                        next.classList.add("cd__next-digit-fade");
                        prev.classList.add("cd__prev-digit-fade");
                    }

                    next.innerHTML = digit;
                    prev.innerHTML = this.time[i];
                }
            });
        }

        this.time = displayDigits;
        // progress in seconds
        const progress = this.el.querySelector("[data-progress]");

        if (progress)
            progress.innerHTML = this.getProgressInSeconds();
        // loop
        clearTimeout(this.animTimeout);
        this.animTimeout = setTimeout(this.clearAnimations.bind(this),500);

        clearTimeout(this.updateTimeout);
        this.updateTimeout = setTimeout(this.update.bind(this,true),1e3);
    }
}

I’m also attaching images of result from codepen, github pages/vs code

codepen.io resultvs code result(same as github pages hosting)

flatpickr js keeps reverting date to Jan 1, 2022

I’m using flatpickr as a datepicker in html/js. I pull the module in using jsdelivr:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

It’s been behaving normally for years, but yesterday it started behaving oddly. Here is my javascript, which I have not changed:

$("input[type='datetime'], input[type='datetime-local']").flatpickr({
        enableTime: true,
          altInput: true,
          altFormat: "F j, Y at h:i K",
          dateFormat: "Y-m-d H:i",
        time_24hr: false
      });

And that displays a datepicker like so:
source code

When I select a date, the value of the datepicker flatpickr-input class changes to the datetime chosen and the datepicker form-control input class changes its name to datepicker form-control input active. I think that’s all expected.

The problem is that when I click a second time (either on another date or outside of the calendar div), the datetime removes my selection and replaces it with 2022-01-01 00:00.

Why is it doing that rather than keeping the value I select?

I want to add some score events using javascript

im new to this and i have this simple code for my game that increases score on click

var count = document.getElementById("score");
var score = 0;
var audio = new Audio('pop.mp3');

function increaseScore(){
    score++;
    count.innerHTML = score;
}

how do i add events like if score is bigger than 100 do a certain thing i already tried

if (score > 100) {

}

and its not workin

Sanity and Next.js is not rendering dynamic page content

I am building a simple blog website with Next.js and Sanity. I am able to render the list of posts on a /blog route, but when I click the link to navigate to a specific post, I am unable to render anything to the screen.

import client from '../../client'

export default function Post({post}) {
  console.log(post)
  return (
    <main className="px-5 m-auto mt-10 max-w-7xl">
      <h1 className="text-5xl font-bold"></h1>
    </main>
  )
}

export const getStaticPaths = async () => {
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)]{
      "params": {
        "slug": slug.current
      }
    }`
  )

  console.log(paths)

  return {
    paths,
    fallback: true,
  }
}

export const getStaticProps = async ({params}) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
    _id,
    _createdAt,
    title,
    author->{
      name,
      image
    }
    mainImage,
    slug,
    body
  }`

  const {slug} = params

  const post = await client.fetch(query, {slug})

  return {
    props: post,
  }
}

How to execute onsubmit method, after setting the html in body.innerHTML asynchronously

I fetched a login form asynchronously, and setted it inside body. I declared it’s on submit form before that, and now getting a Reference error. Is there any way to set onsubmit using html, without having to call loginForm.onsubmit = login.

const result = await fetch('/session');

if (result) {
    const login = await result.text();
    document.body.innerHTML = login;
}

function login(e) {
    e.preventDefault();
    const loginForm = document.getElementById('loginForm');
    console.log(loginForm);
    const options = { method: loginForm.method, body: new FormData(loginForm) };
    const loginButton = document.getElementById('loginButton');
    const loginButtonHTML = loginButton.innerHTML;
    loginButton.innerHTML = 'Loading...';
    disableElements(loginForm);
    // const result = await fetch(loginForm.action, options);
}

The html is:

<form id="loginForm" action="/user/login" method="post" onsubmit="login">
    <input type="text" name="username" autocomplete="username" placeholder="Username">
    <input type="password" name="password" autocomplete="current-password" placeholder="Password">
    <button id="loginButton" type="submit">Login</button>
</form>