Toggle Open Close on multiple divs using vue.js

I’m using vue.js and have a list of items that when clicked opens each individual div. How can I get my button to open each one individually instead of opening all of them when clicked?

I don’t want to pass isOpened as another key, value in my object, so Somehow I need this as being the index of the button getting clicked

vue.js

<div v-for="(item, index) in items" :key="index">
   <div class="item">
       <button @click="toggleItem">Toggle the {{item.name}}</button>
       <div class="toggle-item" v-show="toggled">
          {{ item.name }}
          {{ item.title }}
       </div>
     </div>
 </div>

data

export default {
    data:() => ({
    toggled: false,
      items: [
      {
        name: 'First List',
        title: 'First title'
      },
      {
        name: 'Second List',
        title: 'Second title'
      },
      {
        name: 'third list',
        title: 'third title'
      }
    ]
    }),
     methods: {
        toggleItem: function() {
        this.toggled = !this.toggled;
        }
    }
}

style

.item {
  height: 40px;
  width: 200px;
  background: #cccccc;
  margin-bottom: 20px;
}

.toggle-item {
  background: red;
  height: 100px;
  width: 100px;
}

Search Suggestion based on data from database using JavaScript

I have a website in which I want to add a functionality of searching. I have created the website using ASP.NET and the data is stored in Apache hive. In the search functionality, I want to create a feature wherein the user must get suggestions based on data from database.

There is at least 50 columns in the database and the user could be searching data from any of the columns. I want my search function to recognize what the user is typing and suggest accordingly. I have no function to know which column the user is searching from, it is to be done from the server side. I don’t want to use python as it would be slower.

So any suggestions for what I can do using JavaScript?

position error in localization in react.js

I have the following code that takes the user’s location from a google api, the detail I have is that the accuracy is too high, for example accuracy: 2600.670416166183, I don’t know if someone knows how to solve this error, it would be very useful

const useGeoLocation = () => {
const [location, setLocation] = useState({
    loaded: true,
     coordinates: {
            lat: "",
            lng: "",
        },
    aceptacion: null,
});
const onSuccess = (location) => {
    console.log(location);
    setLocation({
        loaded: true,
        coordinates: {
            lat: resultado.location.lat,
            lng: resultado.location.lng,
        },
        aceptacion:1
    });
};

useEffect(() => {
    const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=......`;
    const http = new XMLHttpRequest();
    http.open("POST", url);
    http.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
        let resultado = JSON.parse(this.responseText);
       let latitude = resultado.location.lat;
       let longitude =  resultado.location.lng;
       setLocation({
            loaded: true,
            coordinates: {
                lat: resultado.location.lat,
                lng: resultado.location.lng,
            },
            aceptacion:1
        });
        console.log(resultado);
        return resultado
      }
    }
    http.send();
}, []);

return location;

};
export default useGeoLocation;

How to clear a Material UI textfield of file type

I’ve tried mutliple approaches, but I cannot seem to clear a Material UI textfield with type="file"

I am limiting the file size, and if a user oversteps the limit, an error message pops up, but the Textfield also needs to be cleared.

Here is my code:

function CreateClaim(props) {

const [supporting_docs, setSupportingDocs] = useState(null);

const handleFileUpload = (event) => {
    event.preventDefault()
    if(event.target.files[0].size > 10971520) {
      setFileError(true)
      setSupportingDocs(null)
    } 
    else {
      setSupportingDocs(event.target.files)
    }
  };

return (

<TextField onChange={handleFileUpload}
   InputLabelProps={{ shrink: true }}
   margin="normal"
   required
   fullWidth
   id="supporting_docs"
   label="Bewys van uitgawe"
   name="supporting_docs"
   type="file"         
   />
)

} export default CreateClaim

The error message works well, but cant clear the Textfield, any suggestions?

Callback function JS

why is the call back function not working?
can someone explain it to me.

function addObj(callback){
    setTimeout( () => console.log("Object has been added."), 5000);
    
    callback();
}


function getObj(){
    setTimeout( () => console.log("Object has been fetched."), 3000);
}

addObj(getObj);

Passing data to leaflet from ag-grid programmitically

I am a total javascript/leaflet/ag-grid newbie, so please bear with me.

I am trying to create a website that allows users to query (add/remove) spatial points on a leaflet map based on selecting rows from ag-grid. I have no understanding/experience with React or Angular, so I am using vanilla javascript. Leaflet is used to display the data spatially.

I have spatial data that has gps coordinates that are parent records. For each parent they have multiple children.

Spatial data

The spatial data is an external file I read into my HTML file. It looks like this:

var spatial_data = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", 
"properties": { "Name": "Boulder 1", "SpatialID": "Lower Blair_0" }, 
"geometry": { "type": "Point", "coordinates": [ -105.39079766, 41.19044516, 2510.159912109375 ] } },

{ "type": "Feature", 
"properties": { "Name": "Boulder 2", "SpatialID": "Upper Blair_1" }, 
"geometry": { "type": "Point", "coordinates": [ -105.39058423, 41.19655902, 2534.4599609375 ] } }
]};


Children records

There are children records for each parent spatial ID. The data is within the .js code

The functionality I am hoping for is someone could filter the ag-grid for a route called ‘Slam Dunk’ and that would provide the “SpatialID”:”Lower Blair_0″. If they filter for ‘Test two’ it provides the same SpatialID. This would be available to play around with in the HTML file.

myownscript.js

var rowData = [{"Route Name":"Slam Dunk","SpatialID":"Lower Blair_0"},
 {"Route Name":"Test two","SpatialID":"Lower Blair_0"},
 {"Route Name":"Test three","SpatialID":"Upper Blair_1"}];

var columnDefs= [
    {field: 'Route Name', minWidth:10, sortable:true, filter:true},
    {field: 'Sub-Area', minWidth:5, sortable:true, filter:true},       
];

const gridOptions = {
    columnDefs: columnDefs,
    rowData: rowData,
    defaultColDef:{
        flex:1,
        minWidth:100
    },
    rowSelection: 'multiple',
    pagination:true,
    onSelectionChanged:onSelectionChanged
};

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
};

function onSelectionChanged(){
    var selectedRows = gridOptions.api.getSelectedRows();
    var selectedData = selectedRows.map(data => data.SpatialID);
  
    var test = selectedData.filter(onlyUnique);
   console.log(test); //This works. But I need to return an array that I can use elsewhere

   return test
};

document.addEventListener('DOMContentLoaded', () => {
    const gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

});

I can easily send ‘test’ to the console. That provides me with the ability to check that my onSelectionChanged() is working; however, I really need to pass the output from onSelectionChanged() as an array. I need to pass that and use that in an embedded script within my html. This is so I can filter the data in my leaflet layers and features.

my html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
   
    <!-- Read in the geojson-->
    <script src='assets/spatialdata.json'></script>

    <script src="https://unpkg.com/[email protected]/dist/ag-grid-community.min.js"></script>
    <script src="myownscript.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="bstrap/js/bootstrap.min.js"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"></script>')</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">
    <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-alpine.css">

  </head>

  <body>
    <script >
        var usefulData = onSelectionChanged() 
        //Lots of leaflet type operations below this, like reading in geojson data.
    </script>
  </body>
</html>


I have tried extensive searching. For some reason, the majority of use cases for gridOptions.api.getSelectedRows() end with an example of using console.log(). I need to actually pass that information along instead of just outputting to the console. I am not sure if this is a misunderstanding on my part for how JS works, or if it is expected behavior from ag-grid, but it doesn’t seem possible. I have tried using global variables like so:

var test;
function onSelectionChanged(){
    var selectedRows = gridOptions.api.getSelectedRows();
    var selectedData = selectedRows.map(data => data.SpatialID);
  
  
    test = selectedData.filter(onlyUnique);
    return test
};
console.log(test);

This doesn’t seem to work as the console.log() in the .js file doesn’t work, and in the script in the HTML it can not find test.

I am primarily a statistician/python programmer, so this a new foray for me. It is likely I am missing a bigger picture thing and if so, I would appreciate alternatives to my current approach.

Would the use of ONLY “vw” and “vh” as units to construct a website and determine the size of elements a good idea?[HTML, CSS, JS] [closed]

Well, I’m a new to HTML and CSS, but I must tell you I learned a lot of stuff. But recently, after building a lot of cool ideas I thought to myself about something that I really hate, and this my friend are “Responsiveness”. One of the stuff that really bothers me is the fact that if someone zooms out or zooms in with “Ctrl + “+”” ou “Ctrl + “-“” breaks my website completely. I Mean it does not “Break” completely, but C’mon,it just bothers me a lot. So as final measure I though to myself if it would be “Smart” to create a JS to create a unit based from VW or VH. But since I have no full experience on it, I don’t know if this idea I had was “dumb”, so, basically, I just wanted to know a set of disadvantages that could hit me using only View Port Unit before I start working on my new project.
Obs(I know VH takes the scroll bar size, but I already did create a program to calculate the width of the bar. I mean, a copied one hehe!).

How to add `asyncWebAssembly: true’` in the `next.config.js` file?

I’m getting following error when I hit npm run dev.

enter image description here

It seems that something is missing in the next.config.js file and it’s about the webpack stuff.

It say’s that I need to enable experiments.asyncWebAssembly: true.

Below is my next.config.js file.

so I added it as below :

next.config.js

/**
 * @format
 * @type {import('next').NextConfig}
 */

const nextBundleAnalyzer = require('@next/bundle-analyzer');
const withPlugins = require('next-compose-plugins');
const withLess = require('next-with-less');

const withBundleAnalyzer = nextBundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
});

const plugins = [
  [
    withBundleAnalyzer,
    {
      enabled: process.env.ANALYZE === 'true',
    },
  ],
  [
    withLess,
    {
      excludeFile: (str) => /*.{spec,test,stories}.tsx?/.test(str),
      lessLoaderOptions: {},
    },
  ],
];

const nextConfig = {
  reactStrictMode: true,
  webpack(config) {
    config.module.rules.push({
      test: /.ya?ml$/,
      type: 'json',
      use: 'yaml-loader',
    });

    config.module.rules.push({
      test: /.svg$/,
      use: '@svgr/webpack',
    });

    experiments = { asyncWebAssembly: true }
    
    return config;
  },
};

module.exports = withPlugins(plugins, nextConfig);

Though it doesn’t works. Throws same error.

So, How should I ahead ? Do I need to add anything more in it?

Using Axios to post a joke on click ( 1 at a time )

I could use some help.
I have a button and on click, it generates a joke using dad jokes API and Axios. However, I can’t figure out how to get rid of the old joke when I click on the button again. Here is my code. Thanks

let button = document.querySelector(‘button’)
button.addEventListener(“click”, getJoke)

 function getJoke() {
const p = axios
.get('https://icanhazdadjoke.com/', { headers: { "Accept": "text/plain" },  
 })


 .then((response) => {
const joke = response.data

const jokeContainer = document.querySelector('.joke'); 

const blockquoteEl = document.createElement('blockquote');

blockquoteEl.append(joke);

jokeContainer.appendChild(blockquoteEl);
 })
  .catch((error) => {
const jokeContainer = document.querySelector('.joke');
jokeContainer.innerText = 'Joke not found :(';

  });

  }




 <div class="joke">
    <button>Click if you want a cringe joke</button>
  </div>

POST request not accepting my GraphQL input

How do I get this post request to work:

{"query":"user(id: "jack") { getDetails { edges { node { name } } } name, description }"}

Even if I use single quotes it still does not work as it is an invalid JSON string.

The authorizations tokens are fine (bearer token)

I am using this site to test the POST request

Embedded video displays playback id error

So I modified a youtube video downloader for a project and the video that is embedded just shows an error. It says “An error occurred. Please try again later. (Playback ID: M-CB0N1oRgwx3evX) Learn More” I have looked at some questions but I can’t get it to work.
My link: “https://youtube.com/embed/LINKHERE”
Here’s the code:

<!DOCTYPE html>
<html>
<head>
  <title>Yt watcher</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="col-md-6 offset-md-3 mt-5">
    <div class="card">
      <div class="card-header bg-info">
        <h5>Yt watcher</h5>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group">
              <label class="text-weight"><b>Online Videos Link:</b></label>
              <input type="txt" name="link" class="form-control link" required>
            </div>
          </div>
        </div>
        <form class="form-download">
          <div class="row">
            <div class="col-md-12">
              <div class="form-group">
  
          <div class="row">
            <div class="col-md-12">
              <div class="form-group mt-4 download-video">
                <button class="btn btn-success btn-block click-btn-down" type="submit">Search</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
<script type="text/javascript">
  $(".click-btn-down").click(function(){
      var link = $(".link").val();
    var fromate = $(".formte").children("option:selected").val();
    var src =""+link+"="+fromate+"";
    downloadVideo(link,fromate);
  });
  function downloadVideo(link,fromate) {
      $('.download-video').html('<iframe style="width:100%;height:300px;border:0;overflow:hidden;" scrolling="no" src="https://youtube.com/embed/'+link+'"></iframe>');
  }
</script>
</html>

How to Use Jquery Smart Wizard with some ajax pages

I am having difficulty in understanding how to use the jQuery smart wizard.

I have managed to get it going with static html for my first three tabs but I now want to add another tab which uses an ajax call to get the data based on the data I have collected in the previous tabs.

I know there are callback functions for leaving and entering steps but the documentation is unclear on how to use them (or it maybe I don’t understand enough jQuery/JavaScript to correctly interpret the documentation)

The way I read it is I would use

$("#smartwizard").on("stepContent", function(e, anchorObject, stepIndex, stepDirection) {
   // if this is the correct step index then
   // do my ajax call using a promise 
   // (Which I do not understand fully how to do. 
   // I have never used a promise before.)
   // and return my html. (Where is the html going to be put? is it the 'tabpanel'?)
   return myHTMLfromtheajaxcall;
  // else do nothing
  // How do I stop it overriding the existing content?
  // Do I return '' or false or what?
});

What and where do the parameters for the function come from. What is ‘e’? What is ‘anchorObject’? The other parameters are self explanatory.

I hope somebody can explain things in simple terms with some examples.

Thank you in advance.