Add Function to change place of element

I want if the local time is in europe that the option europe changes place under the heading “Europe”

This is what I came with:

<select id="timezone" onkeyup="filterFunction(this,event)" onchange="changeTimezone()">
    <option value="local" selected>Local Time</option>
    <optgroup label="Europe" id="europe-optgroup">
        <option value="GMT">London</option>
        <option value="Europe/Amsterdam">Amsterdam</option>
        <option value="Europe/Athens">Greece</option>
        <option value="Europe/Moscow">Moscow</option>
    </optgroup>
    <optgroup label="USA">
        <option value="America/New_York">New York</option>
        <option value="America/Los_Angeles">Las Vegas</option>
    </optgroup>
</select>

and:

var userCountry = ""; // Store user's country here (e.g., obtained through geolocation)

var europeanCountries = ["Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden"];

if (europeanCountries.includes(userCountry)) {
    var localOption = document.querySelector("#timezone [value=local]");
    var europeOptgroup = document.getElementById("europe-optgroup");
    europeOptgroup.appendChild(localOption);
}

request before another request axios

How can i simplify this code? I need to make a request to get the token, before requesting the server to get the data. Then write this token to localstorage so as not to re-call a request for a token.

if (localStorage.getItem('token')) {
  axios.defaults.headers.common["Authorization"] = localStorage.getItem("token");
  axios.post(`${BASE_URL}/json/em/pos/poses`, {
    limit,
    offset,
    contractType: 0,
    ...filter,
  })
    .then((res) => {
      dispatch(reducerGetOutlets({data: res.data, limit, offset: 0}));
    });
} else {
  axios(`${process.env.REACT_APP_BASE_URL}/api/user/info`)
    .then((response) => {
      axios.defaults.headers.common["Authorization"] = "Basic " + response.data.token;
      localStorage.setItem("token", "Basic " + response.data.token);
      axios.post(`${BASE_URL}/json/em/pos/poses`, {
        limit,
        offset,
        contractType: 0,
        ...filter,
      })
        .then((res) => {
          dispatch(reducerGetOutlets({data: res.data, limit, offset: 0}));
        });
    })
}

Why is my alert not popping up once the condition is met? Tic Tac Toe Boardgame

So I am making a Tic Tac Toe project while following The Odin Project curriculum. I have built the board and now I am just testing out some different code piece by piece, before building everything at once. Right now I am trying to validate that I can create a win condition, but does not seem to be working. Here is the code I have currently.

const boxes = $(".box");
const upperRight = $("#upperRight");
let userPlayer;

// Setting all of the actions for player when they click, win, or lose
const players = (player, symbol) => {
  // Function for what happens when the player clicks a square
  const action = () => {
    $(boxes).on("click", function() {
      $(this).css("background-color", symbol);
    });
  };

  // Function for if the player wins
  const win = () => {
    if (upperRight.css("background-color") === "red") {
      alert("You win");
    }
  };

  return { player, symbol, action, win };
};

const player1 = players("Player 1", "red");
player1.action();
player1.win();
.board {
  width: 500px;
  height: 500px;
  margin: 0 auto;

  display: grid;
  grid-template-columns: auto auto auto;
}

.box {
  border: 3px solid;
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="board">
  <div class="box" id="upperLeft"></div>
  <div class="box" id="upperCenter"></div>
  <div class="box" id="upperRight"></div>
  <div class="box" id="middleLeft"></div>
  <div class="box" id="middleCenter"></div>
  <div class="box" id="middleRight"></div>
  <div class="box" id="bottomLeft"></div>
  <div class="box" id="bottomCenter"></div>
  <div class="box" id="bottomRight"></div>
</div>

Where am I loading jquery_ujs in my Rails 6 app?

Bugsnag is reporting this error on many pages: “If you load both jquery_ujs and rails-ujs, use rails-ujs only”

Rails 6.1.3, with webpacker.

application.js:

//
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .

_head.html.erb:

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
<script nomodule="" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>

<script src="//d2wy8f7a9ursnm.cloudfront.net/v7/bugsnag.min.js"></script>

<script>
  <% if current_user.blank? %>
    var currentUser = null;

    Bugsnag.start(
    { 
      apiKey: '<%= BUGSNAG_API_KEY %>', 
      releaseStage: '<%= Rails.env %>'
    });

  <% else %>
    var currentUser = { email: '<%= current_user.email %>' };

    Bugsnag.start(
    { 
      apiKey: '<%= BUGSNAG_API_KEY %>', 
      releaseStage: '<%= Rails.env %>',
      user: { email: '<%= current_user.email %>' }
    });
  <% end %>
</script>


<script src="https://js.stripe.com/v3/"></script>

<%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>

I’ve looked but cannot find jQuery UJS in my code. So why am I getting this error? And how could I remove it? I can’t reproduce it, and cannot tell if this is breaking the UX or is a warning.

Thanks.

Zoom IN issue on map layer with leaflet

I have issue with zoom IN on map layer with leaflet.
After a zoom in max, layer map disappear. Whatever value associated with maxZoom, after a zoom in, layer disappear.
Do you know why ?

Below code elements in my code html page:

map = L.tileLayer(‘https://maps-api.meteoblue.com/v1/tiles/satellite_global/20230608/20230608_1815/{z}/{x}/{y}.jpg?apikey=XXXXXXX’, {maxZoom: 10, tilesize: 512, attribution: ‘Map data © OpenStreetMap contributors, CC-BY-SA‘});

How to download an image in the current page without opening a new tab or changing the current window and such with javascript

For example in this page : https://www.monstermmorpg.com/

I want to download this image into my given target folder

enter image description here

The url of the image is

https://static.monstermmorpg.com/images/HowToPlayTheGame/Main-Game-Screen.webp

So what kind of function i can use in console window of the chrome that would download this image when this page is open without opening any new window tab, or change current window and such

I mean console window of the chrome here

enter image description here

Simply without affecting currently opened window, without changing anything

For Loops in the EcmaScript specification

I have been trying to understand how javascript works under the hood as deep as possible and have been trying to learn the spec simultaneously. I am a bit confused at this description

According to the spec:

14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet )

The abstract operation ForBodyEvaluation takes arguments test (an Expression Parse Node or empty), increment (an Expression Parse Node or empty), stmt (a Statement Parse Node), perIterationBindings (a List of Strings), and labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

 1. Let V be undefined.
 2. Perform ? CreatePerIterationEnvironment(perIterationBindings).
 3. Repeat,
   a. If test is not empty, then
      i. Let testRef be ? Evaluation of test.
     ii. Let testValue be ? GetValue(testRef).
    iii. If ToBoolean(testValue) is false, return V.
   b. Let result be Completion(Evaluation of stmt).
   c. If LoopContinues(result, labelSet) is false, return ? UpdateEmpty(result, V).
   d. If result.[[Value]] is not empty, set V to result.[[Value]].
   e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
   f. If increment is not empty, then
      i. Let incRef be ? Evaluation of increment.
     ii. Perform ? GetValue(incRef).

Now when we look at CreatePerIterationEnvironment, it has this to say:

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (a List of Strings) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

1. If perIterationBindings has any elements, then
  a. Let lastIterationEnv be the running execution context's LexicalEnvironment.
  b. Let outer be lastIterationEnv.[[OuterEnv]].
  c. Assert: outer is not null.
  d. Let thisIterationEnv be NewDeclarativeEnvironment(outer).
  e. For each element bn of perIterationBindings, do
       i. Perform ! thisIterationEnv.CreateMutableBinding(bn, false).
      ii. Let lastValue be ? lastIterationEnv.GetBindingValue(bn, true).
     iii. Perform ! thisIterationEnv.InitializeBinding(bn, lastValue).
  f. Set the running execution context's LexicalEnvironment to thisIterationEnv.
 2. Return unused.

I do not understand what the question mark is on the line Perform ? CreatePerIterationEnvironment(perIterationBindings) means, and when a for loop is executed, since no function is being called a new execution context is not created. Why is it saying here for a normal for loop that if there are any perIterationBindings, that the lastIterationEnvironment should be the running execution context’s LexicalEnvironnment?

Border-Collapse not merging table borders

I’m building a grid using React and HTML <table> elements but I can’t get the borders of each <td> cell to merge.

I’m using a nested for-loop to build out the grid from the grid state. The getInitialGrid function initializes the grid state with a nested array for the rows and columns. I then use the JSX to loop through the grid state to build the grid with each <td> element returning a Node component (which has additional functionality that’s not relevant to this question, so I didn’t include the functions associated with it). Here is my code:

import React, { useState } from "react";

function PathFinder() {
  const [grid, setGrid] = useState(getInitialGrid());

    function createNode(row, col) {
    return {
      row,
      col,
      isStart: row === 10 && col === 15,
      isFinish: row === 10 && col === 35,
    };
  }

  function getInitialGrid() {
    const newGrid = [];
    for (let row = 0; row < 20; row++) {
      const currentRow = [];
      for (let col = 0; col < 50; col++) {
        currentRow.push(createNode(row, col));
      }
      newGrid.push(currentRow);
    }
    return newGrid;
  }

  return (
    <div id="PathFinder">
      <NavBar visualizeAlgorithm={visualizeAlgorithm}/>
      <div id="grid">
        <table>
          {grid.map((row, rowIdx) => {
            return (
              <tr key={rowIdx}>
                {row.map((node, nodeIdx) => {
                  const { row, col, isFinish, isStart } = node;
                  return (
                    <td>
                      <Node
                        key={nodeIdx}
                        col={col}
                        row={row}
                        isFinish={isFinish}
                        isStart={isStart}
                      />
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </table>
      </div>
    </div>
  )
 }

 function Node(props) {
  const {
    col,
    row,
    isFinish,
    isStart
  } = props;

  return (
    <div
      id={`node-${row}-${col}`}
    ></div>
  );
 }

Here is the CSS I have for the grid. I use border-collapse: collapse on the <table> element but the borders do not merge, the gaps between them just get smaller.

#grid {
  display: flex;
  justify-content: center;
  align-items: center;
}

table {
  margin: 100px 0 0;
  border-collapse: collapse;
}

.node {
  min-width: 25px;
  min-height: 25px;
  border: 1px solid rgb(175, 216, 248);
}

This is what my grid looks like. As you can see, there is a small gap between each cell (Node component) and I can’t figure out how to get rid of it.
enter image description here

Outlook desktop client not wrapping text to new lines for Thai emails

I’m building some Thai emails and having trouble to properly break text into lines. While other email clients are doing a great job in breaking text, Outlook is not doing the same and I’ve tried various CSS techniques which did not help. Can anyone pleas help with a way to break the line to next line.

I don’t wanna go with adding line breaks or <br/> as I might introduce unintended word breaks. Just seeing if outlook can do the same other email clients.

 <body style="background-color: #f4f4f4; word-spacing: normal">
    <div style>
      <!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="shell-outlook" role="presentation" style="width:600px;" width="600" bgcolor="#FFFFFF" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]-->
      <div
        class="shell"
        style="background: #ffffff; background-color: #ffffff; margin: 0px auto; max-width: 600px"
      >
        <table
          align="center"
          border="0"
          cellpadding="0"
          cellspacing="0"
          role="presentation"
          style="background: #ffffff; background-color: #ffffff; width: 100%"
        >
          <tbody>
            <tr>
              <td
                style="direction: ltr; font-size: 0px; text-align: center; padding: 0"
                align="center"
              >
                <!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="container-outlook" style="vertical-align:top;width:600px;" ><![endif]-->
                <div
                  class="mj-column-per-100 mj-outlook-group-fix container"
                  style="
                    font-size: 0px;
                    text-align: left;
                    direction: ltr;
                    display: inline-block;
                    vertical-align: top;
                    width: 100%;
                    padding: 0;
                  "
                >
                  <table
                    border="0"
                    cellpadding="0"
                    cellspacing="0"
                    role="presentation"
                    style="vertical-align: top"
                    width="100%"
                  >
                    <tbody>
                      <tr>
                        <td
                          align="center"
                          class="hero-image"
                          style="font-size: 0px; padding: 0; word-break: break-word"
                        >
                          <table
                            border="0"
                            cellpadding="0"
                            cellspacing="0"
                            role="presentation"
                            style="border-collapse: collapse; border-spacing: 0px"
                          >
                            <tbody>
                              <tr>
                                <td style="width: 600px">
                                  <a
                                    href="https://www.tesla.com/event/tesla-energy---mount-gravatt-tech-talk?redirect=no"
                                    target="_blank"
                                  >
                                    <img
                                      alt="Tesla"
                                      height="auto"
                                      src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/df/Microsoft_Office_Outlook_%282018%E2%80%93present%29.svg/512px-Microsoft_Office_Outlook_%282018%E2%80%93present%29.svg.png?20230309112740"
                                      style="
                                        border: 0;
                                        display: block;
                                        outline: none;
                                        text-decoration: none;
                                        height: auto;
                                        width: 100%;
                                        font-size: 13px;
                                      "
                                      width="600"
                                    />
                                  </a>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </td>
                      </tr>
                      <tr>
                        <td
                          align="left"
                          class="title-text"
                          style="font-size: 0px; word-break: break-word; padding: 60px 56px 40px"
                        >
                          <div
                            style="
                              font-family: Arial;
                              font-size: 38px;
                              font-weight: 700;
                              text-align: left;
                              color: #7c7c7c;
                              line-height: 44px;
                            "
                          >
                            เปลี่ยนบ้านของคุณให้เป็น<font color="black" style="line-height: 44px"
                              >&nbsp;พลังงาน</font
                            >
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <td
                          align="left"
                          class="default-text"
                          style="font-size: 0px; word-break: break-word; padding: 0 56px"
                        >
                          <div
                            style="
                              font-family: Arial;
                              font-size: 20px;
                              text-align: left;
                              color: #5c5e62;
                              line-height: 26px;
                            "
                          >
                            <div style="line-height: 26px"><br /></div>
                            <div style="line-height: 26px">
                              โซลูชันการจัดเก็บพลังงานในบ้านที่จ่ายพลังงานให้กับคุณ
                              และเมื่อรวมกับพลังงานแสงอาทิตย์จะช่วยให้คุณสร้างพลังงานที่คุณต้องการเพื่อช่วยจ่ายพลังงานให้กับบ้านและชาร์จอุปกรณ์ในบ้านของคุณได้อย่างยั่งยืน
                            </div>
                            <div style="line-height: 26px"><br /></div>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <!--[if mso | IE]></td></tr></table><![endif]-->
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!--[if mso | IE]></td></tr></table><![endif]-->
    </div>
  </body>

Sample Pictures:
Diff btwn Outlooks and Apple mail pictures

I’ve followed this Stack thread and GoodEmailCode but didn’t got any working solution. I was trying to see if outlook can wrap text to new line as other email clients. All browser clients are working as expected but only issue with Outlook desktop application on Windows. I even tried to build a template on Litmus but saw the issue there as well.

Converting to negative values, but returns negative decimal, instead of negative integer

I’m currently working on a calculator program, and I’m facing an issue with converting a number to a negative value. When I input a positive number and then click the ‘+/−’ button to convert it to a negative value, the display shows a negative decimal value instead of an integer. For example, if I input ‘1’ and then click ‘+/−’, the display shows ‘-1.’ instead of ‘-1’. How can I fix this issue and ensure that the display value remains an integer when converted to a negative number?

let display = "0";
let runningTotal = 0;
let operator;

const screen = document.querySelector("#screen");

var button = document.querySelectorAll(".btn");

for (var i = 0; i < button.length; i++) {
  button[i].addEventListener("click", function (event) {
    buttonClicked(event.target.innerText);
  });
}

// Detects which button is clicked.
function buttonClicked(value) {
  if (isNaN(value)) {
    symFunction(value);
  } else {
    numFunction(value);
  }
  screen.innerText = display;
}

// For displaying numbers to the screen.
function numFunction(numString) {
  if (display === "0") {
    display = numString;
  } else {
    display += numString;
  }
}

// Detects which symbol is clicked and the effect.
function symFunction(symbol) {
  switch (symbol) {
    case "C":
      display = "0";
      runningTotal = 0;
      break;
    case "=":
      if (operator === undefined) {
        return;
      } else {
        calcFunction(parseFloat(display));
        operator = undefined;
        display = runningTotal.toString();
        runningTotal = 0;
      }
      break;
    case "+":
    case "−":
    case "×":
    case "÷":
    case "%":
      mathFunction(symbol);
      break;
    case "+/−":
      negateNumber();
    case ".":
      addDecimal();
  }
}

// Connecting the symbol pressed to the calculation.
function mathFunction(symbol) {
  if (display === "0") {
    return;
  }
  const numDisplay = parseFloat(display);
  if (runningTotal === 0) {
    runningTotal = numDisplay;
  } else {
    calcFunction(numDisplay);
  }
  operator = symbol;
  display = "0";
}

// Handling the calculation.
function calcFunction(numDisplay) {
  if (operator === "+") {
    runningTotal += numDisplay;
  } else if (operator === "−") {
    runningTotal -= numDisplay;
  } else if (operator === "×") {
    runningTotal *= numDisplay;
  } else if (operator === "÷") {
    runningTotal /= numDisplay;
  } else if (operator === "%") {
    runningTotal *= numDisplay / 100;
  }
}

// Change the sign.
function negateNumber() {
  display = "-" + display;
}

// Convert to float.
function addDecimal() {
  if (!display.includes(".")) {
    display += ".";
  }
}

how to save the checkboxes status to local storage and render it back in javascript to-do list?

I am making a to-do list app using basic javascript. I am having a problem with saving the checking status of the checkbox input element and rendering it back when the page is refreshed… I am currently learning javascript, so my whole approach to the checkboxes might need to be changed so tell me about the best method to do so.

here’s the code:

let toDoListArray = JSON.parse(localStorage.getItem("items")) || {
  toDoListArray: [
    {
      inputValue: "wash the dishes",
      dateValue: "1-1-2023",
      check: false,
    },
    {
      inputValue: "checked example 2",
      dateValue: "22-3-2025",
      check: true,
    },
  ],
};

addItem();

// the code i used for the checkboxes
let list = [];

document.querySelectorAll("input[type=checkbox]").forEach((element) => {
  list.push(element);
  let idx = list.indexOf(element);

  if (toDoListArray[idx].check) {
    element.setAttribute("checked", true);
  } else if (!toDoListArray[idx].check) {
    element.removeAttribute("checked");
  }

  element.addEventListener("change", () => {
    if (element.checked) {
      toDoListArray[idx].check = true;
    } else {
      toDoListArray[idx].check = false;
    }
  });
});

//end of checkboxes code


function addItem() {
  let savedText = document.querySelector(".task-input");
  let inputValue = savedText.value;
  let savedDate = document.querySelector(".date-input");
  let dateValue = savedDate.value;
  let check = false;

  if (inputValue) {
    toDoListArray.push({
      inputValue,
      dateValue,
      check,
    });
  }

  addItemHTML();

  savedText.value = "";
  savedDate.value = "";
}

function deleteItem(index) {
  toDoListArray.splice(index, 1);
  addItemHTML();
}

function addItemHTML() {
  let addedHTML = "";

  for (let i = 0; i < toDoListArray.length; i++) {
    let { inputValue, dateValue } = toDoListArray[i];
    addedHTML += `
      <div class="rendered-list-item">
        <input id="check${i}" type="checkbox">
        <label for="check${i}">${inputValue}</label>
        <div>${dateValue}</div>
        <button class="delete" onclick="deleteItem(${i})") >Delete</button>
      </div>
    `;
  }

  let jsonString = JSON.stringify(toDoListArray);
  localStorage.setItem("items", jsonString);

  document.querySelector(".list").innerHTML = addedHTML;
}
* {
  margin: 0 auto;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}
html {
  scroll-behavior: smooth;
}

:root {
  --form-hue: 226;
  --form-saturation: 53%;
  --form-light: 90%;
  --form-bg-color: hsl(
    var(--form-hue),
    var(--form-saturation),
    var(--form-light)
  );
  --header-bg-color: rgba(147, 147, 147, 0.6);
  --header-color: aliceblue;
  --list-bg-color: rgba(201, 199, 223, 0.3);
  --main-bg-color: hsl(221, 70%, 95%);
  --add-color: white;
}

body::-webkit-scrollbar {
  width: 0.25rem;
}

body::-webkit-scrollbar-track {
  background: #c9c9d7;
}

body::-webkit-scrollbar-thumb {
  background: rgb(61, 61, 169);
}

main {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: var(--main-bg-color);
  width: 60%;
  height: 100%;
  padding: 20px;
}

.header,
.form,
.list {
  width: 100%;
  padding: 10px;
  margin: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
.header {
  border-radius: 10px;
  background-color: var(--header-bg-color);
  color: var(--header-color);
  font-weight: bold;
}

.form {
  background-color: var(--form-bg-color);
  border-radius: 10px;
}

.list {
  background-color: var(--list-bg-color);
  border-radius: 5px;
  flex-direction: column;
  width: 100%;
}

.task-input,
.date-input,
.add {
  border-radius: 10px;
  padding: 7px;
  margin: 5px;
  border: none;
  outline: none;
}

.add {
  background-color: hsl(
    var(--form-hue),
    var(--form-saturation),
    calc(var(--form-light) * 0.5)
  );
  color: var(--add-color);
  transition: 0.2s;
}

.add:hover {
  background-color: hsl(0, 0%, 71%);
  scale: 1.07;
  font-weight: bold;
  cursor: pointer;
}

.add:active {
  background-color: aliceblue;
}

.task-input:focus,
.date-input:focus {
  background-color: hsl(240, 33%, 95%);
}

.task-input:hover,
.date-input:hover {
  outline: 2px solid rgba(62, 93, 152, 0.6);
}

@media only screen and (max-width: 600px) {
  main {
    width: 100%;
  }
}

.rendered-list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  background-color: hsl(0, 100%, 100%);
  border-radius: 10px;
  padding: 5px;
  margin: 5px;
  width: 95%;
  flex-wrap: wrap;
}

.list .rendered-list-item:nth-child(even) {
  background-color: hsla(222, 32%, 88%, 0.824);
}

.list .rendered-list-item:nth-child(even) div:nth-child(3) {
  color: hsla(224, 43%, 72%, 0.824);
}

.rendered-list-item:hover {
  background-color: hsla(0, 0%, 100%, 0.824);
}

.rendered-list-item label,
div,
button {
  padding: 10px;
  border-radius: 10px;
  border: none;
}

.rendered-list-item button {
  align-self: normal;
  transition: 0.2s;
  margin-right: 5px;
  color: hsl(0, 0%, 71%);
}

.rendered-list-item button:hover {
  scale: 1.08;
  background-color: hsl(0, 65%, 55%);
  color: white;
  cursor: pointer;
}

.rendered-list-item div:nth-child(3) {
  color: hsl(0, 0%, 71%);
}

.rendered-list-item label:nth-child(2) {
  background-color: hsl(233, 100%, 98%);
  margin-left: 5px;
  flex: 1;
  transition: 0.5s;
}

.rendered-list-item input[type="checkbox"]:checked + label {
  font-weight: bold;
  text-decoration: line-through;
  color: hsl(0, 0%, 71%);
}

.rendered-list-item input[type="checkbox"] {
  align-self: normal;
  margin-left: 5px;
  opacity: 0.6;
  accent-color: hsl(262, 25%, 56%);
  width: 0.9rem;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vanilla javascipt ToDoList</title>
  </head>
  <body>
    <main>
      <p class="header">To-Do-List</p>
      <div class="form">
        <input placeholder="type the task" type="text" class="task-input" />
        <input type="date" class="date-input" />
        <button class="add" onclick="addItem()">Add</button>
      </div>
      <div class="list"></div>
    </main>
  </body>
</html>

as u can see, I tried iterating through the checkboxes to add a “checked” attribute to the ones with the index that corresponds with the saved to-do-list array index and also add an event listener to each element to see if they are checked and change their corresponding to-do list object’s check property, but when the page is reloaded the array’s check property returns back to false and no checked attributes are rendered. when I console log the to-do list array after the event listener and I check the checkbox, the array’s check attribute gets updated to true but once I refresh the page, it becomes false again.

S3 getObjectCommand doesn’t return the latest version of the file

I am using react and i am trying to get a json file from S3.

This is the package i use: "@aws-sdk/client-s3": "^3.332.0".

This is the code i run in order to get the s3 object:

import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import env from "../env";

export const getS3Object = async ({
  tempCredentials,
  bucketName,
  objectKey,
}) => {
  try {
    if (!bucketName || !objectKey || !tempCredentials) {
      console.log(
        "No bucket name or object key or temp credentials was provided."
      );
      return;
    }
    const credentials = {
      accessKeyId: tempCredentials?.AccessKeyId,
      expireTime: tempCredentials?.Expiration,
      secretAccessKey: tempCredentials?.SecretAccessKey,
      sessionToken: tempCredentials?.SessionToken,
    };
    const s3 = new S3Client({
      region: env.REACT_APP_REGION,
      credentials,
    });
    const params = {
      Bucket: bucketName,
      Key: objectKey,
    };
    const command = new GetObjectCommand(params);
    const response = await s3.send(command);
    const responseString = await response.Body.transformToString();
    const result = JSON.parse(responseString);
    return result;
  } catch (error) {
    console.log(error);
  }
};

I have a json file sitting in s3 bucket that is used for texts in my app.

The json is in the bucket and i have overridden it with a new json file with changed texts.

When i run the code above i keep on getting the same initial version of the json, in other words the texts in the app haven’t changed.

The weird thing is i have an app in react native that is using the same code to get texts from the same bucket and if i edit a text and upload it to the bucket all i need to do is close and re open the app and the text is changed…

I have object versioning enabled if that helps.

TL;DR

This is what i tried:

  1. Test: Running a react app that access a s3 bucket to get a json file after i uploaded the same json but with some changes.

    Result: Getting the first json without the changes.

  2. Test: Running a react native app that access the same s3 bucket to get a different json file after i uploaded the same json but with some changes.

    Result: Getting the new json with the changes.

Put request in JavaScript ajax like a form submit

I’m trying to update by using PUT method. Where form doesn’t support put method, I’m trying it through ajax call. I don’t know how the backend will be getting the values through post call from form. I’m trying to implement the same using ajax.

Tried Map. But it’s taking it as an object. And key value form is not happening.

Please help me to do so.

function updateRecord(divId) 
    {
        var map = new Map();
        var hiddenField;
        var divNode = document.getElementById(divId);
        var inputNodes = divNode.getElementsByTagName('INPUT');
        for(var i = 0; i < inputNodes.length; ++i)
        {
            var inputNode1 = inputNodes[i];
            var inputVale = inputNode1.value;
            var inputName = inputNode1.name;
            
            map.set = (inputName,inputVale);
        }
        
        let contextURL = 'http://localhost:8080/LocationWeb/LocCon/updateLocationValues/';
        let parmURL = contextURL + map;
        var xhr = new XMLHttpRequest();
        xhr.open("PUT", parmURL, true);
        xhr.send();
        xhr.onload = function() 
        {
            if (xhr.status != 200) 
            {
                console.log('ERROR');
            }
            else
            {
              listAllPageCall();
            }
        };
        xhr.onerror = function()
        {
            window.location = 'http://localhost:8080/LocationWeb/LocCon/listAllLocations';
        };
    }

My backed spring boot code is like this.

 @PutMapping("/updateLocationValues")
public String updateLocationValues(@ModelAttribute("location") Location location, ModelMap resModMap)
{
    locationService.updateLocation(location);
    List<Location> allLocations = locationService.getAllLocation();
    resModMap.addAttribute("allLocations", allLocations);
    return "displayAllLocations";
}