Save data from html input to .csv file

I have created a form using HTML, CSS and js only and I wanted to data from that form to a CSV file locally don’t want to use php and such. Let’s say my from have first name, date of birth, some radio buttons and some drop-down menus and on submit I wanted to save all the data in a .csv file.

Thanks in advance and any advice will be helpful

redux reducer… + 1 I have created a new array and added one. now how do I put it back together and return the new state

so found the index of what I want to change, I created a new array newFavorites and increased a value on one of its keys (sets +1). But I am not sure how to return the new state with the updated key value.

  case ADD_SETS: 
                const favToIncreaseSet = state.favoritedExercises.findIndex(fav => fav.id === action.payload.id);
                const newFavorites = [...state.favoritedExercises];
                let repIncreasedFav = newFavorites[favToIncreaseSet].sets + 1;
               
                
                return { ...state, newFavorites}

Update array of objects depend on values from another array [duplicate]

The array of Objects and different arrays with values. Need to know how to update the data object depended on that value. Value in array matches id in data. Thx much for help

{
   "data":[
      {
         "id":1,
         "name":"name1",
         "active":false
      },
      {
         "id":2,
         "name":"name2",
         "active":false
      },
      {
         "id":3,
         "name":"name3",
         "active":false
      }
   ]
}

Array of values

values = [1,3]

How should look

{
   "data":[
      {
         "id":1,
         "name":"name1",
         "active":true
      },
      {
         "id":2,
         "name":"name2",
         "active":false
      },
      {
         "id":3,
         "name":"name3",
         "active":true
      }
   ]
}

Download audio file from html with javascript function

I’m trying to download an mp3 file on the click of a button, it downloads, but the file it downloads is not correct, it’s a WAY smaller file than the original one (25 bytes), while the original one is 10MB.

It’s my first time working with downloading stuff so I’m pretty clueless.

Here’s some code:

JS function:

 function download(i) {
    var audio = document.getElementById("audio"+i);

    const blob = new Blob(, {type:"octet-steam"});

    const href = URL.createObjectURL(blob);

    const a = Object.assign(document.createElement("a"), {
        href, 
        style: "display:none",
        download: "myAudio.mp3",
    });
    document.body.appendChild(a);

    a.click();
    URL.revokeObjectURL(href);
    a.remove();
}

Audios are identified by their ID and their file name comes from the data I have in a database.
HTML/PHP

for($i=0; $i<$count; $i++){
  $res = mysqli_fetch_array($result);
  echo('<tbody id="tbody">
  <tr>
  <audio id="audio'.$i.'" src="mp3/'.$res["song_artist"].'-'.$res["song_title"].'.mp3"> 
  <td><button onclick="download('.$i.')">&#8628</button></td>
  </tr>
</tbody>');
}    

Check if half of a period has passed

I have a system where the user can choose a period where after this period he earns for example + 2% of the sum he has chosen. If he tries to make an action with this sum before the half of the period it loses a percentage of its value. So what I want to know is how to calculate half of a date.

In my example:

I have for example in a mysql table the date when he put the sum and the date when the defined period will be finished.
So if it is 24-2-2022 and he chooses in 6 months, there will be two pieces of information in the database 24-2-2022 and 24-8-2022.
What I’ve done so far is split() the date to separate day, month and year. But here I am stuck because I do not know how to compare all this to see if the period is halfway or not.

open children and close other children in multi-level navigation

I am working on a navigation and now managed to open up deeper levels of a certain parent one by one on click but I have a hard time trying to figure out how to close all others when going into a another direction.

Let’s say you have A1, A2A, A3A and A4A open and you click on B1, then I want A1A, A2A and A3A to close. But it also needs to work midway: let’s say you have A1, A2A, A3A and A4A open but you click on A2B then A3A and A4A need to close.

$('li.has-children').click(function(){

        $(this).children('.wrap').addClass('active');
        
    });
.wrap {
  display:none;
}

.active {
  display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="has-children">
    <a class="">link A1</a>
    <div class="wrap wrap-0">
    <ul>
      <li class="has-children">
        <a class="">link A2A</a>
        <div class="wrap wrap-1">
        <ul>
          <li class="has-children">
            <a class="">link A3A</a>
            <div class="wrap wrap-2">
              <ul>
                <li class="has-children">
                  <a class="">link A4A</a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
        </div>
      </li>
      <li class="has-children">
        <a class="">link A2B</a>
        <div class="wrap wrap-1">
        <ul>
          <li class="has-children">
            <a class="">link A2B</a>
            <div class="wrap wrap-2">
              <ul>
                <li class="has-children">
                  <a class="">link A3B</a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
        </div>
      </li>
    </ul>
    </div>
  </li>
  <li class="has-children">
    <a class="">link B1</a>
    <div class="wrap wrap-0">
    <ul>
      <li class="has-children">
        <a class="">link B2A</a>
        <div class="wrap wrap-1">
        <ul>
          <li class="has-children">
            <a class="">link B3A</a>
            <div class="wrap wrap-2">
              <ul>
                <li class="has-children">
                  <a class="">link B4A</a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
        </div>
      </li>
      <li class="has-children">
        <a class="">link B2B</a>
        <div class="wrap wrap-1">
        <ul>
          <li class="has-children">
            <a class="">link B3B</a>
            <div class="wrap wrap-2">
              <ul>
                <li class="has-children">
                  <a class="">link B4B</a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
        </div>
      </li>
    </ul>
    </div>
  </li>
</ul>

TypeError: discord_js_1.Intents is not a constructor after making a timeout command?

so I was coding the timeout command and when I wanted to try it out I got the following error

TypeError: discord_js_1.Intents is not a constructor

Before even having the timeout command and when I made the timeout command I suddenly got this error.

Here is my timeout code:

const { CommandInteraction } = require("discord.js");

module.exports = {
    name: "timeout",
    description: "Timeout a member.",
    options: [
        {
            name: "user",
            description: "Member to perform the timeout on",
            type: "USER",
            required: true
        },
        {
            name: "length",
            description: "Length of the timeout.",
            type: "STRING",
            required: true
        },
        {
            name: "reason",
            description: "Reason for this timeout.",
            type: "STRING",
            required: true
        }
    ],
    /**
     * 
     * @param {CommandInteraction} interaction 
     */
    async execute(interaction){
        const user = interaction.options.getUser("user")
        const length = interaction.options.getString("length")
        const reason = interaction.options.getString("reason")
        const member = interaction.guild.members.cache.get(user.id)

        const timeInMs = ms(length);
        if(!timeinMs) return interaction.followUp("Please specify a valid time!");

        member.timeout(timeInMs, reason)
        interaction.followUp(`${user} has been timeouted for ${length}! (${reason})`)

    }
};

I don’t know why I am suddenly getting this error, could someone help me about this?

Application being able to self update with github

I’m creating a bot app with Node.JS and I’d like to make it able to update its dependecies automatically without needing to turn it off and do it manually, I want that the bot itself could programatically use the “npm update”.

But more important than that, I want that it could self update its own code if I make a “git push” on its repo. However, I don’t want to do it with every push, just chosen ones. After researching, I found GitHub Actions, but I’m still a little lost about it.

Thanks in advance.

How to get the result from a forEach loop?

I have the code below, which is working (i.e. I can print the index to the console). However, I’d like to use that index outside of the forEach loop. I have tried random things like returning the tabIndex, wrapping it all in a function etc. but I don’t get it right or understand the steps needed.

The plan is to use the index to fetch data from a JSON file.

Any suggestions on how to make the result from tabIndex globally available?

/* DESTINATION TABS */
    const destinationTabs = document.querySelectorAll(".destination-info--tab");
    
    /* Get index of the clicked tab */
    destinationTabs.forEach((destinationTab) => {
      destinationTab.addEventListener("click", (e) => {
        const tabIndex = Array.from(destinationTabs).indexOf(e.target);
        console.log(tabIndex);
      });
    });

WordPress Category & Sub-category Dropdown search

Is there any way to create a select search with 2 dropdowns in WordPress – 1 for the Parent Category & 1 For the Sub-Category which changes based on the parent category chosen?

It’s for future projects I just need to know if it’s possible and which route to go with this functionality. I’m aware of the normal WordPress category search and I’ve tried the https://free.searchandfilter.com plugin but this displays all categories even the subs into one dropdown.

It would basically look something like the snippet below:

<!-- Parent Category Select -->
<select>
  <option value="slow">Slow</option>
  <option value="Fast">Fast</option>
  <option value="Fastest">Fastest</option>
</select>


<!-- Sub-Category Select -->
<select>
  <option value="Toyota">Toyota</option> <!-- Slow category -->
  <option value="Subaru">Subaru</option> <!-- Fast category -->
  <option value="mercedes">Mercedes</option> <!-- Slow category -->
  <option value="audi">Audi</option> <!-- Fastest category -->
</select>

<button>
Submit
</button>

Подключение БД к JS-проекту [closed]

Создаю приложение с использованием Яндекс Карт. Суть: получение из БД координат и показ точек на карте. Карты и подключение к БД по отдельности работают корректно. Но когда делаю подключение к БД до создания карты, то на карте не отображаются точки. Если подключаюсь к БД после создания карты, точки есть, но в консоли браузера ошибка “Uncaught TypeError: Net.connect is not a function”
Код:

const mysql = require('mysql2');

let sqlArr = [];


const conn = mysql.createConnection({
    host: "localhost", 
    user: "логин сервера",
    database: "база данных",
    password: "пароль",
    port: 3307
});

conn.connect(function (err) {
    if (err) {
        return console.error("Ошибка: " + err.message);
    }
    else {
        console.log("Подключение к серверу MySQL успешно установлено");
    }
});

let query="SELECT * FROM test";

conn.query(query, (err, result, field) =>{

    console.log(result);
    sqlArr = result;

});


ymaps.ready(init);


let placemarks = [
    {
        latitude: 59.97,
        longitude: 30.31,
        hintContent: 'This is hint',
        balloonContent: 'This is balloon'
    },
    {
        latitude: 59.95,
        longitude: 30.31,
        hintContent: 'This is hint2',
        balloonContent: 'This is balloon2'
    },
    {
        latitude: 59.96,
        longitude: 30.31,
        hintContent: 'This is hint2',
        balloonContent: 'This is balloon2'
    }
];

let geoObjects = [];

function init(){

    let map = new ymaps.Map("map", {
        center: [59.94, 30.32],
        zoom: 12,
        controls: ['zoomControl'],
        behaviors: ['drag']
    });

    for(let i = 0; i < placemarks.length; i++){
 
        geoObjects[i] = new ymaps.Placemark([placemarks[i].latitude, placemarks[i].longitude], 
        {
            hintContent: placemarks[i].hintContent,
            balloonContent: placemarks[i].balloonContent
        }, 
        {
            iconLayout: 'default#image'

        },
        {
            iconContent: 'Hello'
        }
        );
        
    }; 

    let clusterer = new ymaps.Clusterer({});

    map.geoObjects.add(clusterer);
    clusterer.add(geoObjects);

}

Использую NodeJS + Parcel

Jest – testing Link (next/link)

I am trying to write unit tests to confirm my nav links work correctly.
My MainNavigation.js file:

import Link from 'next/link';

const MainNavigation = () => {
  return (
    <header>
      <div>
        <Link href='/'>The React Parks</Link>
      </div>
      <nav>
        <ul>
          <li>
            <Link href='/all-parks'>All Parks</Link>
          </li>
          <li>
            <Link href='/new-park'>Add a New Park</Link>
          </li>
        </ul>
      </nav>
    </header>
  )
};

export default MainNavigation;

My test file:

import '@testing-library/jest-dom'
import { fireEvent, render, screen } from '@testing-library/react';
import MainNavigation from './MainNavigation';

describe('MainNavigation', () => {
    describe('links', () => {
    jest.mock('next/link', () => ({ children }) => children);

    it('should redirect to '/' when clicking on "The React Parks" text', () => {
      render(<MainNavigation />);

      const parksString = screen.getByText('The React Parks');
      fireEvent.click(parksString);
      expect(parksString.closest('link')).toHaveAttribute('href', 'https://');
    })
  });
});

How can I maybe include checking if the URL matches certain string? Or would it make sense to do something like assign a constant to render different pages and expect that constant to match some text on the other pages? How would one go about testing this functionality?

How can I get the event when user type a URL and go to it?

I saw on a website that we can see when a use try to refresh the page ( using F5 or clicking the refresh button ) in this way:

if (performance.navigation.type === 1)

My question is: Let’s say the user don’t refresh the page but he type another URL to my other page. How can I get that event?

I say that because I have stored in my Redux state if user is logged in. When the page is type another URL, my state is lost. So, I want to catch that moment and check if I have a token in localstorage.

Is it possible to insert a span at a paragraph range? It gets problematic if the paragraph already has spans

I am trying to insert a new span into a paragraph that already has spans. If the paragraph doesn’t have any spans the inserting of the new span works perfectly.

But it gets messed up when one or more spans already exists in the paragraph. Is it even possible to make this work?

At the last 3 lines of the function is where the paragraph gets put back together to insert the new span in between. I am having trouble converting the split paragraph back into a HTML format, it always seems to stay like a string or something else is getting in the way. You can get an idea by running the code and selecting some text, it will insert the span at the mouseup event.

function replaceSelectedParagraphTextBySpan() {
  // get range and text of selected text in paragraph
  let text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }
  
  const storedSelections = []
  const currSelection = window.getSelection();
  for (let i = 0; i < currSelection.rangeCount; i++) {
    storedSelections.push(currSelection.getRangeAt(i))
  }
  const rangeStart = storedSelections[0].startOffset
  const rangeEnd = storedSelections[0].endOffset

  // our paragraph
  const textObject = document.getElementById('textObject')

  const frontParagraph = textObject.innerHTML.substring(0, rangeStart)
  const backParagraph = textObject.innerHTML.substring(rangeEnd, textObject.length)
  // I tried here to convert the front and backParagraph into a paragraph element because instead it
  // just remains a string
  const pElementFront = document.createElement('p').innerHTML = frontParagraph
  const pElementBack = document.createElement('p').innerHTML = backParagraph

  // create our span for inserting
  const span = document.createElement('span')
  span.innerHTML = " <this text got added> "

  // insert new span into paragraph at selected range
  textObject.innerHTML = pElementFront
  textObject.appendChild(span)
  textObject.innerHTML = textObject.innerHTML + pElementBack
}

const paragraph = document.getElementById('textObject')
paragraph.addEventListener('mouseup', e => {
  replaceSelectedParagraphTextBySpan()
})
<p id="textObject"><span>Select some </span>text and the selected text will get replaced by a span</p>