How to change global variable with addEventListener?

I’m trying to change the userSelection variable with addEventListener. Nothing is showing up from the console.log at the bottom, but I get the desired result when placed in the button variables. I understand that it becomes local when inside the buttons instead of global, but have confusion on how addEventListener works.

var userSelection = "";
var rock = document.querySelector('#rock');
var paper = document.querySelector('#paper');
var scissors = document.querySelector('#scissors');

rockButton = rock.addEventListener('click', e => {
  userSelection = "Rock"
})

paperButton = paper.addEventListener('click', e => {
  userSelection = "Paper"
})

scissorButton = scissors.addEventListener('click', e => {
  userSelection = "Scissors"
})

console.log(userSelection);

Any help or pointer in the right direction would be greatly appreciated!

Is there a way to have chatgpt answer in an altert?

I asked ChatGPT to make me a bookmarklet that alerts the user and prompts to ask a question, then using the user’s input and alerting the answer back. It generated this code after lots and lots of trying and it still doesn’t work:

javascript:(async function() {
  const question = prompt("What is your question?");
  const typingIndicator = document.createElement("div");
  typingIndicator.textContent = "ChatGPT is typing...";
  typingIndicator.style.position = "fixed";
  typingIndicator.style.bottom = "20px";
  typingIndicator.style.left = "20px";
  typingIndicator.style.background = "rgba(255, 255, 255, 0.9)";
  typingIndicator.style.padding = "10px";
  document.body.appendChild(typingIndicator);

  const response = await fetch("https://api.openai.com/v1/engines/davinci/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer INSERT_YOUR_API_KEY_HERE"
    },
    body: JSON.stringify({
      prompt: question,
      max_tokens: 1024,
      temperature: 0.7
    })
  });
  
  const data = await response.json();
  typingIndicator.remove();
  alert(data.choices[0].text);
})();

(Yes, I did enter my own API key, I just removed it here for security reasons)
What’s wrong with the code?

I asked it over and over again to troubleshoot and regenerate the code with different guidelines, but to no avail. The only reason I’m asking ChatGPT is because I’m really inexperienced with javscript. What happens is the prompt shows up, and you enter the question. At the bottom left of the screen, “ChatGPT is typing…” pops up for not even half a second and leaves the question unanswered.

“These buttons are not for you” Discord.js

I’m using discord.js to make a bot command. This command replies with a set of buttons that a user can click. I am trying to make it so that if another user clicks the button, it replies with an ephemeral message saying that they cannot click the buttons.
Currently, the ephemeral message sends to the person that used the slash command, instead of the person clicking on the buttons.

How to use linear interpolation on bezier curves

I am writing a javascript program that is to create an object, which has a direction (a triangle for ease) that will go around a bezier curve which is based on any number of points. The program allows you to add and move the points however you please.

for (let i = 0; i <= thePoints.length - 2; i++) {
    //fixes last line as it was weird for some reason (line before the loop)
    if(i == thePoints.length - 2){
      const lastPoint = thePoints[thePoints.length - 2];
      const pt0 = thePoints[thePoints.length - 3];
      const pt1 = thePoints[thePoints.length - 1]; //first point in the array
      const pt2 = thePoints[0];
      const v1 = [(pt1[0] - pt0[0]) * 0.5, (pt1[1] - pt0[1]) * 0.5];
      const v2 = [(pt2[0] - lastPoint[0]) * 0.5, (pt2[1] - lastPoint[1]) * 0.5];
      context.beginPath();
      context.moveTo(lastPoint[0], lastPoint[1]);
      context.bezierCurveTo(lastPoint[0] + (v1[0]/3), lastPoint[1] + (v1[1]/3), pt1[0] - (v2[0]/3), pt1[1] - (v2[1]/3), pt1[0], pt1[1]);
      context.stroke();
    }
    else{
    const pt0 = thePoints[i === 0 ? thePoints.length - 1 : i - 1];
    const pt1 = thePoints[i];
    const pt2 = thePoints[i + 1];
    const pt3 = thePoints[i + 2] || pt0;
    const v1 = [(pt2[0] - pt0[0]) * 0.5, (pt2[1] - pt0[1]) * 0.5];
    const v2 = [(pt3[0] - pt1[0]) * 0.5, (pt3[1] - pt1[1]) * 0.5];
    context.beginPath();
    context.moveTo(pt1[0], pt1[1]);
    context.bezierCurveTo(pt1[0]+(v1[0]/3), pt1[1]+(v1[1]/3), pt2[0]-(v2[0]/3), pt2[1]-(v2[1]/3), pt2[0], pt2[1]);
    context.stroke();
    }
  }

  //draws the last segment of the track
  const lastPoint = thePoints[thePoints.length - 1];
  const pt0 = thePoints[thePoints.length - 2];
  const pt1 = thePoints[0]; //first point in the array
  const pt2 = thePoints[1];
  const v1 = [(pt1[0] - pt0[0]) * 0.5, (pt1[1] - pt0[1]) * 0.5];
  const v2 = [(pt2[0] - lastPoint[0]) * 0.5, (pt2[1] - lastPoint[1]) * 0.5];
  context.beginPath();
  context.moveTo(lastPoint[0], lastPoint[1]);
  context.bezierCurveTo(lastPoint[0] + (v1[0]/3), lastPoint[1] + (v1[1]/3), pt1[0] - (v2[0]/3), pt1[1] - (v2[1]/3), pt1[0], pt1[1]);
  context.stroke();
  
  
}

Here is said code which creates the path or track which the object has to follow. So how would I go about interpolating the points? Making sure the triangle remains on the path, as well as points in the direction of motion. (Arc length parameterization is not needed, it can speed up and slow down at certain points). The param is a number 0-number of points which again, can be any. If the param was 1.5, the triangle would be between points 1 and 2 of the path.

I have tried linear interpolation, but this only works with straight lines the way I did it, so I am not sure how to adjust it for bezier curves.

Dynamic form submission in Vue 2

My goal is to be able to create multiple forms, on page. Then be able to submit them. I have a component, let’s call it FormComponent. The JS works like this

 name: "ax-form",
  components: {},
  props: {
    endPoint: String,
    id: String,
    model: Object,
    mode: String,
    formModel: [Array, Object],
    name: String,
  },
  data() {
    return {};
  },
  methods: {
    async onSubmit() {
      console.log("submit called");
      if (mode === "create") {
      ... do stuff
      } else if (mode === "update") {
      ...do stuff
      }
    },
  },

Odd enough, if the onSubmit function is called in the “update” mode. There is no issue calling the function. If called in the “create” mode. No stuff is done. Is this a binding issue? Can Vue not handle dynamic binding to functions and if so how do I achieve such?

I have tried creating a mixin component as well. Thinking maybe this was a binding problem. Though, no luck.

Odd jquery behaviour when moving text between fields

I have 2 textboxes, the first has an id of storytxt and the second textbox is dynamically generated in js.

In the second textbox I am setting the value like so

value=" + $('#storytxt').val() + "

When I type into #storytxt text box, and I run the script all works great until I use any white space. The outputs are:

Single words:

<input class="story" id="q1" type="text" value="Test">

Multiple words:

<input class="story" id="q3" type="text" value="Test" this="">

Desired outcome:

<input class="story" id="q3" type="text" value="Test this">

I can’t workout why jquery is parsing the text the way it is, unless .val on a text object doesn’t like whitespace or is it an encoding issue?

Having problems with remove() to remove an input from a to do application

I am trying to build a simple to do application as a starter JS project and have pretty much got it working minus one problem I am stuck on!. When editing the saved task, the input which is created and inserted to edit the task doesn’t disappear once the edited task is saved. I though editInput.remove() would remove the created element from the once the save button was clicked. Is my approach wrong? Any pointers or comments here would be greatly welcomed!

Here is the JS for code I currently have, current issue is with the remove()

const todoInput = document.querySelector(".todo--input");
const addBtn = document.querySelector(".todo--btn-add");
const list = document.querySelector(".todo--list");

window.onload = loadSavedTasks;

function taskFormat(task) {
  const addedItem = document.createElement("li");
  addedItem.className = "todo--listItem";

  const addedText = document.createElement("p");
  addedText.textContent = task;
  addedText.className = "todo--text";

  const btnContainer = document.createElement("div");
  btnContainer.className = "button-container";

  const editBtn = document.createElement("button");
  editBtn.textContent = "Edit";
  editBtn.className = "todo--btn-edit";

  const deleteBtn = document.createElement("button");
  deleteBtn.textContent = "Delete";
  deleteBtn.className = "todo--btn-delete";

  //append to dom
  list.appendChild(addedItem);
  addedItem.appendChild(addedText);
  addedItem.appendChild(btnContainer);
  btnContainer.appendChild(editBtn);
  btnContainer.appendChild(deleteBtn);

  editBtn.addEventListener("click", () => {
    const taskText = addedItem.querySelector(".todo--text");

    const editInput = document.createElement("input");
    editInput.type = "text";
    editInput.value = taskText ? taskText.textContent : "";

    if (taskText) {
      taskText.replaceWith(editInput);
    } else {
      addedItem.appendChild(editInput);
    }

    editBtn.textContent = "Save";
    editBtn.addEventListener("click", () => {
      if (taskText) {
        taskText.textContent = editInput.value;
        editInput.replaceWith(taskText);
      } else {
        const addedText = document.createElement("p");
        addedText.textContent = editInput.value;
        addedText.className = "todo--text";
        addedItem.insertBefore(addedText, btnContainer);
        editInput.remove();
      }
      editBtn.textContent = "Edit";
      saveTasksToLS();
    });
  });

  deleteBtn.addEventListener("click", () => {
    list.removeChild(addedItem);
    saveTasksToLS();
  });
  return addedItem;
}

// load tasks
function loadSavedTasks() {
  if (localStorage.getItem("todoTasks") === null) return;
  let tasks = [...JSON.parse(localStorage.getItem("todoTasks"))];
  tasks.forEach((task, i) => {
    const taskListItem = taskFormat(task.task);
    list.appendChild(taskListItem);
  });
}

function addTask() {
  const newTask = todoInput.value;

  const taskListItem = taskFormat(newTask);
  todoInput.value = "";
  list.appendChild(taskListItem);
  saveTasksToLS();
}

function saveTasksToLS() {
  let tasks = [];
  const taskElements = list.children;

  for (let i = 0; i < taskElements.length; i++) {
    console.log(taskElements[i].querySelector(".todo--text").textContent);
    const taskText = taskElements[i].querySelector(".todo--text").textContent;
    tasks.push({ task: taskText });
  }

  localStorage.setItem("todoTasks", JSON.stringify(tasks));
}

// EVENTLISTENERS
addBtn.addEventListener("click", addTask);

How to get data back from OpenAI API using javascript and display it on my website

I have simple form on my website with text input. We want to make a call to OpenAI API to ask ChatGPT to find some similar companies based on a job description that a user pastes in the text box. So far, haven’t been able to get the return data to work. It is correctly sending the job description data, but not able to list a list of companies. Please look at the javascript code and help.

const form = document.querySelector('form');
const generateButton = document.querySelector('#generate-button');
const companiesOutput = document.querySelector('#output-companies');

function generateCampaign(event) {
  event.preventDefault();
  const jobDescription = document.querySelector('#job-description').value;

  fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      prompt: `Give me 20 top-tier VC backed startup companies in the same space as the company in this job description:nn ${jobDescription}`,
      max_tokens: 50,
      temperature: 0.7
    })
  })
  .then(response => response.json())
  .then(data => {
    const companiesList = data.choices[0].text;
    companiesOutput.innerHTML = `<li>${companiesList}</li>`;
  })
  .catch(error => console.error(error));
};

form.addEventListener('submit', generateCampaign);

Is it possible to repeat event on ics file every 12 hours per event using RRULE?

I have 7 different events per day and i want each events repeat twice or repeat every 12 hours perday

As you can see on my RRULE RRULE:FREQ=DAILY;INTERVAL=1;BYHOUR=10,22 I want to repeat each event per day twice which is 10:00am StartTime and EndTime 10:10pm and I want it to repeat the event maybe 10:00 pm to 10:10 pm.

When I import the ics file on google i cant see the 10:00 pm event. Anyone here tried to repeat the event every 12 hours per event?

This is my JS function to create and download ics file:

  function downloadICSFile(calendarEvents) {
    const calendarBody = calendarEvents
      .map(event => {
        const {
          uid,
          summary,
          description,
          location,
          startDateTime,
          endDateTime
        } = event;

        return `BEGIN:VEVENTrn` +
        `UID:${uid}rn` +
        `SUMMARY:${summary}rn` +
        `DTSTAMP:${getCurrentDateTime()}rn` +
        `DTSTART:${startDateTime}rn` +
        `DTEND:${endDateTime}rn` +
        `DESCRIPTION:${description}rn` +
        `LOCATION:${location}rn` +
        `END:VEVENTrn`;
    })
    .join('');

    const icsFileContent = `BEGIN:VCALENDARrn` +
    `VERSION:2.0rn` +
    `CALSCALE:GREGORIANrn` +
    `PRODID:-//ZContent.net//Zap Calendar 1.0//ENrn` +
    `METHOD:PUBLISHrn` +
    `${calendarBody}` +
    `RRULE:FREQ=DAILY;INTERVAL=1;BYHOUR=10,22rn` +
    `END:VCALENDARrn`;


    console.log(icsFileContent);

    const element = document.createElement('a');
    element.setAttribute(
      'href',
      'data:text/calendar;charset=utf-8,' + encodeURIComponent(icsFileContent)
    );
    element.setAttribute('download', 'SevenDayProgram.ics');
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }

**Output ICS file:
**

BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//ZContent.net//Zap Calendar 1.0//EN
METHOD:PUBLISH
BEGIN:VEVENT
UID:iXW6N29mmJZaro3YqhSr0n
SUMMARY:Eat Banana
DTSTAMP:20230313T023413Z
DTSTART:20230308T020000Z
DTEND:20230308T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:GowEApFmJFDZsV7antQAK6
SUMMARY:Eat Apple
DTSTAMP:20230313T023413Z
DTSTART:20230309T020000Z
DTEND:20230309T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:V-sx_UGcq35CNTW3tWxmK-
SUMMARY:Eat Mango
DTSTAMP:20230313T023413Z
DTSTART:20230310T020000Z
DTEND:20230310T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:siCmwmobGdIShuexZPk0OL
SUMMARY:Eat Strawberry
DTSTAMP:20230313T023413Z
DTSTART:20230311T020000Z
DTEND:20230311T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:kgoUAa3rIAgpptWyNRAPOu
SUMMARY:Eat Watermelon
DTSTAMP:20230313T023413Z
DTSTART:20230312T020000Z
DTEND:20230312T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:kJb6oHgmm94JncGVXj96D4
SUMMARY:Eat Pineapple
DTSTAMP:20230313T023413Z
DTSTART:20230313T020000Z
DTEND:20230313T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
BEGIN:VEVENT
UID:_uReNzwJi6AZUyz6-ERXvD
SUMMARY:Eat Lettuce
DTSTAMP:20230313T023413Z
DTSTART:20230314T020000Z
DTEND:20230314T021000Z
DESCRIPTION:Example event 1
LOCATION:
END:VEVENT
RRULE:FREQ=DAILY;INTERVAL=1;BYHOUR=10,22
END:VCALENDAR

Java script not call a function on changing the value of a input field

I have bootstrap modal form with multiple input. One input field which contains the name of states and show the corresponding region on another field. The moments I change the value of state field the value of region should be changed.it is not working with my code,what is wrong with tis htlml code is

<div class="col-md-4 form-group"style="padding-right:0px;" >
  <div class="form-group">
    <label for="Region" >State</label>
    <?php 
      $sql="select rid,statename,region from tblregion order by statename";
      $stmt=$dbh->prepare($sql);
      $stmt->execute();
      $arrstate=$stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>
    <select class="form-control" name="state" id="state" >
      <option value="<?php echo htmlentities($result->state);?>"><?php echo htmlentities($result->statename);?></option>
      <?php
        foreach($arrstate as $state){
          ?>
          <option value="<?php echo $state['rid']?>"><?php echo $state['statename']?></option>
          <?php
        }
      ?>
    </select>
  </div>
</div>

<div class="col-md-2 form-group" style="padding-left:0px;">
  <label for="Region" >Region</label>
  <select class="form-control" name="" id="region" readonly>
    <option><?php echo htmlentities($result->region);?></option>
  </select>
</div>

The CODE FOR JAVA SCRIPT is

<script>
  $(document).ready(function(){
    jQuery('#state').change(function(){
      //alert("hello);
      var rid=jQuery(this).val();

      jQuery.ajax({
        type:'post',
        url:'get_data.php',
        data:'id='+rid,
        success: function(result) {
          jQuery('#region').html(result); 
          //alert(result);
        }
      }); 
    });
  });
</script> 

How to prevent API abuse from Chrome extension?

I’m writing a Chrome extension that connects to an API. When a user installs the extension, a client ID is generated and stored in local storage:

function getRandomToken() {
    var randomPool = new Uint8Array(32);
    crypto.getRandomValues(randomPool);
    var hex = '';
    for (var i = 0; i < randomPool.length; ++i) {
        hex += randomPool[i].toString(16);
    }
    return hex;
}

Each API request to the backend includes this client ID. The backend uses the client ID to figure out what information to update.

The problem I’m running into is this: with very simple dev tools, one can see what endpoint is being hit. They can then manually send requests to this endpoint with fake client IDs.

Any ideas on how I can prevent this kind of abuse? I added an IP address rate limit on the server-side but wondering how to solve this properly.

Negating string in mongodb

enter image description here

I’m working with node and mongo 5. I am trying to select the field “TOTAL VALUE” with a value other than ‘$0.00’ . I think I’m able to select for ‘$0.00’ with:

{'TOTAL DUE': {$regex: /$0./}}

as in the screenshot. However trying to negate this with:

{'TOTAL DUE': {$not :{$regex: /$0./}}}

gives the entire data set (including when TOTAL DUE does not exist),

How can I get this working?

I want to use JavaScript async/await

Given the following code:

function timer1(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("1...");
    }, 1000);
  })
}
function timer2(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("2...");
    }, 2000);
  })
}
function timer3(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("3...");
    }, 3000);
  })
}
async function timers(){
  await timer3();
  await timer2();
  await timer1();
}
timers();

The output is:

(After 3 seconds..)
3...

I want to get this result:

(After 3 seconds..)
3...
(After 2 seconds..)
2...
(After 1 seconds..)
1...

Why is only one(3…) printed?
I want to print out all three.

useLazyQuery in Apollo always returning null at first click

I am using Apollo Client and the useLazyQuery hook to execute a query on mouse click. I am having a problem though that the data always returns null the first time I click. If I click the button again, the data comes back from the API. How can I make it so that I do not need to click the button twice to get the query response?

const [
    fetchHacker,
    { loading: hackerLoading, error: hackerError, data: hackerData },
  ] = useLazyQuery<IHacker>(GETHACKER)
  const [
    fetchPartner,
    { loading: partnerLoading, error: partnerError, data: partnerData },
  ] = useLazyQuery<IPartner>(GETPARTNER)
  const [
    fetchMentor,
    { loading: mentorLoading, error: mentorError, data: mentorData },
  ] = useLazyQuery<IMentor>(GETHACKER)
  const {
    hacker,
    setHacker,
    partner,
    setPartner,
    mentor,
    setMentor,
  } = useGlobalContext()
  const router = useRouter()

  const handleClick = async (
    e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
  ): Promise<void> => {
    e.preventDefault()
    if (!email || !validateEmail(email)) {
      setEmailError('Please enter a valid email address')
    }
    await fetchHacker({ variables: { email } })
    await fetchPartner({ variables: { email } })
    await fetchMentor({ variables: { email } })
    if (!hackerLoading && hackerData) {
      setHacker(hackerData.getHacker)
      router.replace('/hacker-form')
    } else if (!partnerLoading && partnerData) {
      setPartner(partnerData.getPartner)
      router.replace('/partner-form')
    } else if (!mentorLoading && mentorData) {
      setMentor(mentorData.getMentor)
      router.replace('/mentor-form')
    } else {
      router.replace('/signup')
    }
  }
 <button
type="submit"
className="hover:shadow-form rounded-md bg-[#6A64F1] py-3 px-8 text-base font-semibold text-white outline-none"
onClick={(e) => handleClick(e)}
 >
 Submit
</button>