JavaScript Getting second cell value when clicked on a button on the same row

I did a lot of research but can’t find a solution for this.
How could i get email cell value when i click on the button which is located at the last cell of the same row.

Please check this screenshot for better understanding what i mean

So when i click Button 1, i wanna get Email1 value or when click Button 2, i wanna get N2 cell value.

I found this function but it return the clicked cell value not the one i need:

`

      function getElementID(){
        var tbl = document.getElementById("Results");
      if (tbl != null) {
          for (var i = 0; i < tbl.rows.length; i++) {
              for (var j = 0; j < tbl.rows[i].cells.length; j++)
                  tbl.rows[i].cells[j].onclick = function () { getval(this); };
          }
      }
      function getval(cel) {
          alert(cel.innerHTML);
      }
      }

`

Any help is really appreciated

I found this function but it return the clicked cell value not the one i need: 

`

function getElementID(){
   var tbl = document.getElementById("MyTable");
   if (tbl != null) {
      for (var i = 0; i < tbl.rows.length; i++) {
         for (var j = 0; j < tbl.rows[i].cells.length; j++)
             tbl.rows[i].cells[j].onclick = function () { getval(this); };
          }
      }
    function getval(cel) {
        alert(cel.innerHTML);
      }
      }

`

the for loop isn’t looping on the code of the DOM [duplicate]

The code is expected to print a div that has a title for the product and description of it for 10 times.

let myDiv = document.createElement("div");
let myHeading = document.createElement("h3");
let myParagraph = document.createElement("p");

let myHeadingText = document.createTextNode("Name of  product");
let myParagraphText = document.createTextNode("Description of product");
myDiv.className = "product"; 
for (let i = 1; i < 11; i++) {
    document.body.appendChild(myDiv);
    
    // Add heading text
    myHeading.appendChild(myHeadingText + i);
    
    // Add heading to the main Div
    myDiv.appendChild(myHeading);
    
    // Add paragraph text
    myParagraph.appendChild(myParagraphText + i);
    
    // Add paragraph to the main Div
    myDiv.appendChild(myParagraph);  
    
}

But the loop is not working and I don’t know what the problem is .

Save an ES6 promise to a variable to use elsewhere [closed]

I’m new to async JS so I’m currently tryna make my way through using promises.

I have the following function that returns a promise in either its resolved or rejected state:

export const getGeographicalCoordinates = locationName => {
    fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${locationName}&limit=1&appid=${KEY}`)
    .then(response => response.json())
    .then(data => {
        const p = new Promise((resolve, reject) => {
            if (!(data.length)) {
                return reject(new Error(`${locationName} is not a valid location`));
            } else {
                return resolve([data[0].lat, data[0].lon]);
            }
        })
        return p;
    })
}

I want to then use the function like this:

btn.addEventListener('click', e => {
    getGeographicalCoordinates(location).then(value => console.log(value))
});

However I get the following error Uncaught TypeError: (void fetch(...).then(...).then(...)) is undefined.


I’m confused because when I make the following changes by adding the next method inside the function itself (and remove the next method after the function call from earlier), there’s no error and works as intended:

export const getGeographicalCoordinates = locationName => {
    fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${locationName}&limit=1&appid=${KEY}`)

    ... // (code cut out for brevity)

    .then(value => console.log(value)) // doesn't error and logs as intended.
}

If anyone is able to explain what is happening and help to point me towards a solution to my problem that’d be great!
Thank you

find string in field of object – Javascript

I have string:

city = 'Hải Phòng'

and an array that I get from an API which looks like this:

data = [{},{},{},{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' },{},{}]

I want to find an object in my data:

mycity = data.find( c=>c.TenTinhThanh.includes(city))

the above gives undefined, but I expect

{ MaTinhThanh: 'xx', TenTinhThanh: 'Hải Phòng' }

My API endpoint is:

https://donhang.vnpost.vn/api/api/TinhThanh/GetAll

I am using visual code, Axios, nodejs

I also tried the getting the length of both strings:

data[3].TenTinhThanh.length` ====>11
city.length` ====>9

What is the problem?

Is there any document event to detect specifically window close and send current data with postMessage?

Given the following code

window.addEventListener("visibilitychange", () => {
   // do something here
    if (iframe)
            iframe.contentWindow.postMessage({
              type: "visit_close",
              page: document.title,
              time: timeSpentOnPage,
              shop: key,
              user: member_id,
            });
}

Is there any other reliable way to check if window is closing. Problem with visibilitychange event is that it gets fired on both load and unload.

As far as I remember, unload event is not reliable.

Jank in CSS transform animation

I’m getting some jank/stutter in my animation in my React App. I have a simple carousel with infinite scroll. But I’m getting the jank when I look at the site on my phone and when I try to use .scss instead of css files. You can see the jank/stutter in the attached codepen. All of the css is in index.scss. HTML and javascript are in App.js. Please let me know if you need any more info, this has been driving me crazy.

https://codesandbox.io/s/codepen-with-react-forked-zq6lly?file=/src/components/App.js

Problems importing a p5.js library into a TypeScript project running a p5 Instance

I have recently been trying to switch from JavaScript to TypeScript, and just started a new p5.js project based on a p5.js TypeScript template

My project:

https://github.com/rsegrest/Nodes-and-Edges/tree/trying_to_import_p5.experience_library

The template I started with:

https://github.com/fal-works/p5js-template-petr-plus

Right now I am trying to see if I can use a couple of the libraries available on the p5.js website (under “Libraries”). The first I have been trying to import is called p5.experience, but I have been running into one problem after another getting it to work well with the rest of my project.

I have tried importing the p5.experience library as a script in my index.html file, and also directly inside the project. I don’t think there are any type definitions, so I am trying to bring it into my Typescript environment as Javascript, which seems to be causing a few problems.

I usually have to do a lot of configuration (and trial and error) on TypeScript projects, and have made some modifications to this template, including setting up Jest for unit testing. I had to work through configuring tsc and eslint for allowing JS file and TS files to exist side-by-side, but I believe I have that part of the puzzle worked out…(?)

However, I see that when the p5.experience.js file is loaded it is supposed to augment the functions available in p5, but it is choking on some functions like “stroke” that it may be assuming to be global.

Here is the project branch where I am trying to import the project, and the link points to the branch where I was trying and so far failing to import the library:

https://github.com/rsegrest/Nodes-and-Edges/tree/trying_to_import_p5.experience_library

Thanks for reading, and I would really appreciate any pointers or direction you all could give me, or just tell me what all I am doing wrong!

Easier way to display day.js in multiple locations?

I’m currently studying web development and I’m hoping one of you guys may help.

I’m currently coding the mandatory weather app that everyone and his dog has made lol.

My problem is that on the homepage I have 3 cards displaying with 3 different cities.
I want to display the current date underneath each city by using class=”date”.

But to do it in 3 instances on the same I’ve had to use date,date2 and date3. Which I’m thinking a for loop or something similar could easily fix rather than defining it 3 times.

Any help appreciated!
Thanks!

HTML

<section class="row">
            <h2>  Cities</h2>
            <section class="row">
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    London 
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Birmingham
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date2" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="mb-2 col-xs-12 col-md-6 col-lg-4">
                <div class="card">
                  <h3 class="card-header">
                    Wolverhampton
                  </h3>
                  <div class="card-body">
                    <p>
                      <span id="date3" class="date">date </span> <br/>
                      Temp:<span id="temp"></span> 
                      Wind:<span id="wind"></span>
                      Humid:<span id="humid"></span>
                    </p>
                  </div>
                </div>
              </div>
            </section>
          </div>
          <div class="col-xs-12 col-lg-3">
            <h2>Search</h2>
            <input class="Search col-12 border-radius pb-1" placeholder="Enter City" id="search">
            <ul class="list-group mb-2 pb-2">
                <li class="list-group-item">An item</li>
                <li class="list-group-item">A second item</li>
                <li class="list-group-item">A third item</li>
                <li class="list-group-item">A fourth item</li>
                <li class="list-group-item">And a fifth one</li>
              </ul>
          </div>
          <div class="col-xs-9 col-lg-9">
            <h2 class="subtitle">Results:</h2>
            <!--search results class="results-item"-->
          </div>
        </section>

JavaScript/JQuery

let nowDate = now.format('D / M / YY')
let date = $('#date')
let date2 = $('#date2')
let date3 = $('#date3')
date.text(nowDate);
date2.text(nowDate);
date3.text(nowDate);

Using JavaScript, how can I create an array with a specific width (number of columns)?

I have an array of columns that represents a row of data in a grid.

It looks something like the following:

let row = [rowId,'string value', 'string value 2', 'string value 3'];

I need to generate a dynamic row of data depending upon a variable number of columns the row will have. In other words, I need the array to be initialized so it contains the id and then X number of columns (depending upon the variable number of columns the grid will have).

[id, 'col-1', 'col-2', ...]

I currently have a ridiculous method which works and looks like the following:

getNewRow(maxKey: number, rowWidth: number){
    switch (rowWidth){
      case 1:{
        return [maxKey, 'col 1'];
        break;  
      }
      case 2:{
        return [maxKey, 'column 1', 'col 2'];
        break;  
      }
      case 3:{
        return [maxKey, 'column 1', 'col 2', 'col 3'];
        break;  
      }
      case 4:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4'];
        break;  
      }
      case 5:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5'];
        break;  
      }
      case 6:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6'];
        break;  
      }
      case 7:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7'];
        break;  
      }
      case 8:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8'];
        break;  
      }
      case 9:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9'];
        break;  
      }
      case 10:{
        return [maxKey, 'column 1', 'col 2', 'col 3', 'col 4', 'col 5', 'col 6', 'col 7', 'col 8', 'col 9', 'col 10'];
        break;  
      }
    }

maxKey is just a simple way of insuring that the id column gets set to a new unique value.

My Questions

  • Is it possible to generate a row of data like this dynamically?
  • Is there some way to create a an array on the fly that has a dynamic width (based on the number of columns)?

How to assign a Singular Keys Array to Multiple Nested Value Arrays

I want to assign the keys in (arr1) to the strings in each nested array in (arr2).
I am only a month into learning javascript, and have been stuck on this problem and have been trying to find a working method.

Given the following arrays:

 arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"] //KEYS I WANT TO ASSIGN TO EACH STRING
 arr2 = [["1997-06-01","75","80","65","78","79","3000"],
         ["1997-06-02","70","75","60","73","74","3300"],
         ["1997-06-03","80","85","70","83","84","3800"],...] // THERE ARE 10,000+ OF THESE STRINGS

I want the output to create objects that look like this:

var newArray = [
{
  Date: "1997-06-01",
  Start: "75",
  High: "80",
  Low: "65",
  End: "78",
  AdjEnd: "79",
  Amount: "3000"
}

{
  Date: "1997-06-02",
  Start: "70",
  High: "75",
  Low: "60",
  End: "73",
  AdjEnd: "74",
  Amount: "3300"
}

{
  Date: "1997-06-03",
  Start: "80",
  High: "85",
  Low: "70",
  End: "83",
  AdjEnd: "84",
  Amount: "3800"
}

//continuing through all nested arrays

I can get the format I am looking for with this code, but it is not practical for thousands of arrays.

var result1 = {};
arr1.forEach((key, i) => result1[key] = arr2[0][i]);

var result2 = {};
arr1.forEach((key, i) => result2[key] = arr2[1][i]);


// result3 and so on

var allresult = [result1, result2] //add result3 and so on
console.log(allresult);

Fetching an url to an image from API results in a 302 error

I am making a website in which I load images and other data from an API that is owned by someone else. The data is received in json format.

The response looks a bit like this:

{
  ...
  "users": [
    {
      "name": "John Doe",
      "profile_image": "https://api.<url>/img/<id>",
      "date_created": "<date>",
      ...
    },
    ...
  ]
  ...
}

The issue I’m facing is that when I fetch these posts using JavaScript and want to use the profile_image as the src for an <img> tag, I sometimes (not always) get an response of 302 as supposed to the 200 I want, and the image won’t load as a result of that.

My JavaScript looks kinda like this (very simplified):

function fetchUsers() {
  return fetch(url)
    .then(response => response.json())
    .catch(error => console.log(error));
}

async function loadUsers() {
  let users = await fetchUsers()
  users.forEach(user => {
    userDiv.innerHTML += createUser(user);
  });
}

function createUser(user) {
  return `
    <div>
      <h3>${user.name}</h3>
      <img src="${user.profile_image}">
    </div>
  `;
}

When I follow the url I got from the API myself in the browser I get send to the image without any problems.

I suspect that it has to do with the fact that the image url seems to be linking to another API containing the images. I also noticed that in the DevTools console I see an error about Cross-Origin Read Blocking (CORB) blocking a cross-orign response.

Does anyone have experience with this problem and might be able to help?

Would be greatly appreciated!

regular expression in javascript

I’m trying to create regex for the following validation:

  1. 5 to 15 characters
  2. only letters and numbers allowed
  3. no numbers at the beginning or the end

/^[A-Za-z][A-Za-z0-9]([A-Za-z0-9]+)$/
this for the 2nd & 3rd validation

so how can I add 5 to 15 characters validation to this regexp
I tried to write it like that but it doesn’t work
/^[A-Za-z][A-Za-z0-9]([A-Za-z0-9]+){5,15}$/

How can I save the data fetched from an API in Node.js´ global variable?

function request2API(option){
    const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2
const request = new XMLHttpRequest();
request.open('GET',  urlStart + ChList[option].videosList + keyPrefix + key);
request.send();
request.onload = ()=> {
    if(request.status === 200){
        const response = JSON.parse(request.response);
        console.log(response) //At this point the Object respond exists
        return response;
    };
};
};

let indexChannel = inputFunction("n Pick an option ")
let fetchedData = request2API(indexChannel); //By this point it has died
console.log(fetchedData);

I’ve tried to assignt the fetched data to a variable as one would do in regular javascript for a browser but it’s not working.