Given a total # of items and items per row, what column does an item belong to?

I have an application using CSS grid which will contain an variable number of grid elements, although I’ll know the # of items in each row – is there an easy way to determine the column # of a given item?

ie. given 32 elements arranged into rows of 8, element number 9 is in column 1, element number 10 is in column two.

Currently I’m doing this:

function getColumn(itemIndex, colsPerRow) {
  // its in the last column
  if (itemIndex % colsPerRow === 0) {
    return colsPerRow;
  }

  return itemIndex - (Math.floor(itemIndex/colsPerRow) * colsPerRow);
}

And it returns the correct answer, but I feel like there’s a more simple way to solve this.

Using conditional within HTML

I’m building some HTML within a javascript loop based on an object that has a few different attributes. The one I’m concerned with here is ‘featured’. Only a few elements have this set to 1, the rest are 0.

What I’m trying to achieve is to have the badge class and the title “Featured” added in a div on the elements where featured == 1.

I tried using this conditional operator within the html block but now my front-end just shows 50-60 divs with the featured badge even though I only have 2 that actually have featured set to 1, so I feel like the syntax may be wrong somewhere.

Basically, I want everything else in the HTML to show for every element, but I only want the div with class “badges” to show if featured == 1 on the element.

What am I doing wrong here?

stores.forEach(function (store, index) {
    var name = store.ttle;
    var url = store.link;
        var img = store.imgs;
        var link = store.link;
        var area = store.area;
        var featured = store.featured;
    
            storesHtml += `
                <div class="store-container" style="margin-bottom:15px;">
                  <div class="row">
                    <div class="col-lg-7">
                      <img class="img-fluid" src="${img}">
                    </div>
                    <div class="col-lg-5">`+(featured == 1)?`
                      <div style="" class="badges">
                        <div class="popularContainer">Featured</div>
                      </div>`:`<div></div>
                      <div class="name">
                        <a class="map-trigger" href="#">${area}</a>
                      </div>
                      <div><p style="font-size:10px;">${name}</p></div>

                    </div>
                  </div>
                </div>
                <hr>
            `
    
      });

How to make an e commerce website [with code]

I have been working with Web Development for long but I cannot configure till now how to build e commerce website with code [like JavaScript or PHP]. Can somebody explain how can I build an ecommerce website that can do transactions when the credit or debit card information is entered by the user

Typescript Filter Array of Objects by Duplicate Properties

I have an array of objects I would like to filter to return objects with duplicate property values.

My Array of Objects:

values = [
  { id: 1, name: 'a' },
  { id: 2, name: 'b' },
  { id: 3, name: 'c' },
  { id: 4, name: 'a' }
];

The result I would like to have in a new array of objects:

duplicateValues = [
  { id: 1, name: 'a' },
  { id: 4, name: 'a' }
];

Remove only the first unnecessary letter from a string

for learning purposes I want to remove only the FIRST letter ‘a’ from a string using a function. My function however removes ALL letters ‘a’ from the given string.

function removeFirstLetterA(str) {
  let letterA = 'a';
  for (let i = 0; i < str.length; i++) {
    if (str[i] === letterA) {
      str = str.replace(letterA, '');
    } 
}

return str;
}

Can anyone see my mistake and give any tips?

Keep-alive not working in VueJS3 to use caching in router-view

I am using VUE3, quasar and typescript in my project, and i always used components defined in my routes(that means i never call components from parent component). I have an index page where products are listed when the user searches and paginates something and go to edit page of the product and go back to index page i want user to see his search state, i mean the keyword and pagination where he left. In short, user needs to see the page as he left. For this i have to prevent page from re-render when going back to previous page. I used keep-alive and all its variations to make this happen. so here is my index.vue where i call the router-view

router-view(v-slot="{ Component }")
  keep-alive
    component(:is="Component" :key="$route.name")

and here is how i declare my routes,

{
   path: 'products',
   name: 'Products',
   component: () => import('@/pages/products/index.vue'),
},

When user clicks any edit button where products are displayed here is the code of the button

q-btn(:to="{ name: 'ProductsDetail', params: { _id: props.row._id } }")

How can i solve this?, i tried every Stackoverflow question to fix this but none of them works. What am i doing wrong?

Trouble using ternary operator in template literal

I am trying to insert an anchor element in a template literal if the result comes back as an error. ESLint is throwing an error stating “Unexpected token, expected ;”.

Can someone please tell me how to resolve?

const message = `
  <div class="message">
    <h2>${title}</h2>
    <p>${body}</p>
    `${result === 'error' ? '<a href="#">link</a>' : ''}`
  </div>`;

How to embed Preset Dashboard/Charts in React/Next.js app?

I created a sample pie chart in a published dashboard, then I copied <iframe /> code snippet from “Share > Embed code” and pasted in a /test page.

export default function Test() {
  return (
    <>
      <iframe
        width="600"
        height="400"
        seamless
        frameBorder="0"
        scrolling="no"
        src="https://c2e8b9ae.us2a.app.preset.io/superset/explore/p/G48PLPkAFEJ/?standalone=1&height=400"
      ></iframe>
    </>
  );
}

But it shows “manage.app.preset.io refused to connect“. Please help me, what I am doing wrong?

Cannot update global state using Context.API

Trying to use Context.API to create a global state and pass it to multiple components. The state will store a few properties including a TwilioToken, device type and a name. I have a component SignupForm that renders a button. When the button is clicked, this triggers a function handleSubmit that takes a username and passes the username as an argument to another function setupTwilio. This function sends the username to an end point that interacts with Twilio Programmable Voice API, sending back a TwilioToken and device type. I then want to update my global state with the Twilio Token and device type and then redirect the user to another page /rooms

Problem is I don’t seem to be updating my global state at all, when I console.log(state.TwilioToken) in the component rendered after handleSubmit I get null

Here is my context provider:

const initialState = {
    nickname: '',
    selectedRoom: null,
    rooms: [],
    createdRoomTopic: '',
    twilioToken: '',
    device: null
};

const RoomContext = createContext(null);

export const RoomContextProvider = ({ children }) => {
    const[state, setState] = useState(initialState);
    return (
        <RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
    )
};

export const useGlobalState = () => {
    const value = useContext(RoomContext)
    if(value === undefined) throw new Error('Please add RoomContextProvider');
    return value;
}

My signupform

import { useGlobalState } from '../../context/RoomContextProvider';
...
//without useState() I get the error Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

const [state, setState] = useState(useGlobalState()); 
...
    const handleSubmit = e => {
        e.preventDefault();
        const nickname = user.username;
        setupTwilio(nickname);
        history.push('/rooms');
    }
    const setupTwilio = (nickname) => {
        console.log('inside setupTwilio function', nickname)
        fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`)
        .then(response => response.json())
        .then(data => {
            const twilioToken = data.token;
            const device = new Device(twilioToken);
            device.updateOptions(twilioToken, {
                codecPreferences: ['opus', 'pcmu'],
                fakeLocalDTMF: true,
                maxAverageBitrate: 16000
            });
            device.on('error', (device) => {
                console.log("error: ", device)
            });
            setState((state) => {
                return {...state, device, twilioToken}
            });
        })
      ...
    };
    return (
       <button className="button button-primary button-wide-mobile button-sm"
               onClick={handleSubmit}> Start Coding
       </button>

    );

When I console.log my state in the component rendered I get null

import { useGlobalState } from '../../context/RoomContextProvider';
...
const [state, setState] = useState(useGlobalState());
console.log('global state token is', state.twilioToken)

Javascript Image Upload [File Not Found]

I am trying to implement image upload to a project but Chrome inspector says that the file cannot be found. The HTML seems okay. Not too sure about the CSS and Javascript. Is this some sort of security measure/firewall issue? I’m using a Mac if that helps.

const image_input = document.querySelector("#image_input");
var uploaded_image = "";

image_input.addEventListener("change", function(){
    const reader = new FileReader();
    reader.addEventListener("load", () => {
        uploaded_image = reader.result;
        document.querySelector("#display_image").style.backgroundImage = 'url(${uploaded_image})'
    });
    reader.readAsDataURL(this.files[0]);
})
body{
    display: flex;
    justify-content: center; 

    align-items: center;
    gap: 10px;
    flex-direction: column;
    height: 100vh;
}


#display_image{
    width: 375px;
    height: 211px;
    border: 1px solid black;
    background-position: center;
    background-size: cover;
}
<!DOCTYPE html>
<html>

<link rel="stylesheet" href="style.css">
    
    <head>
    </head>
    <body>
        
<title>Document</title>
<input type= "file" id="image_input" accepts="image/png, image/jpg"> 
     <div id="display_image"></div>
     <script src="script.js"></script>


        
  
      
   
       
           
           
            
  
    
        
    </body>
</html>

leaflet js map not updating marker and circle point when i search some another city dont know what is problem in code? See picture

when I search city in search bar than another city it show marker and circle on both location previous city and current city like so. if u see picture it will tell you what i am saying. help me to imporve the code.

See problem

<div class="container-fluid d-flex flex-column align-items-center area">
        <div class="search-area">
            <input type="text" placeholder="City" id="search">
            <button id="clickme" type="button">Search</button>
        </div>

    <div id="map"></div>
</div>



clickme.addEventListener("click",my=(e)=>{
          e.preventDefault();
          var city=search.value;
          fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=ac3673a8887645fc3d0493904a348e03`)
          .then(response=> response.json())
          .then(data=>{
              var lat=data.coord.lat;
              var long=data.coord.lon;
              var udata=data.name;
              var latlng = L.latLng(lat, long);    
              map.panTo([lat,long],13);
              var circle = L.circle([lat, long], {
                color: 'red',
                fillColor: '#f03',
                fillOpacity: 0.5,
                radius: 1000
            }).addTo(map);
            var marker= L.marker(latlng).addTo(map)
              var popup = L.popup()
              .setLatLng(latlng)
              .setContent(udata)
              .openOn(map);
               console.log(data.name);
              
              });
          });

path url split() find() angular

I have urls and I want to recover the beginning of the path but I don’t know how to do it and being a beginner according to my research I should use the split() and find() method.

Here are the urls:

/test/someurls

/angular/someurls

I need to get /test and /angular is it possible to do that?

Thanks in advance.

Mapping of two dictionary values with same key in javascript

I need to map the values of two dictionaries that have same keys as below and have them in an array:

Input :

 test_dict1 = {“1” : [4, 10], “2” : [8, 6], “3” : [9, 3]},
 test_dict2 = {“1” : [n1, n2], “2” : [n2, n3], “3” : [n4, n5]} 

Output:

[[4,n1],[10,n2],[10,n2],[6,n3],[9,n4],[3,n5]]

What is the best way of doing this?

Could I get my form data from formspark with js fetch() API?

As I read from formspark documentation we can use GET methods in formspark. If I understood correctly, the GET method in JS fetch() API means that we want to retrieve data from somewhere. So I wrote this code to get my data (data that were created before from submissions in formspark) with JS fetch method:

async function fetchText() {
    let response = await fetch('https://submit-form.com/my-id', {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
        }
    })
    let data = await response.json();
    console.log(data);
    return data;
}

fetchText().then(r => console.log(r));

But it gives me an empty object as a response data! while I have six submissions in my account now. Could someone please help me that what is wrong in my code?