Drop down filter

HI I have created a filter functionality, which has two dropdowns, on the basis of selection of these dropdowns select it shows the results, but I want to modify it a little, what I am trying to achieve is, on select of single dropdown it should also show the result, which is currently not showing, please help me modify this code`

<script>
  $('#city, #state').on('change', function(){
    // set reference to select elements
    var city = $('#city');
    var state = $('#state');

    // check if user has made a selection on both dropdowns
    if ( city.prop('selectedIndex') > 0 && state.prop('selectedIndex') > 0) {
        // remove active class from current active div element
        $('.result.active').removeClass('active');
        
        // get all result divs, and filter for matching data attributes
        $('.result').filter('[data-city="' + city.val() + '"][data-state="' + state.val() + '"]').addClass('active');  
  
    }
});
  
  
</script>
<style>
  .result {display:none;}
.result.active {display:block;}
</style>  
<!-- partial:index.partial.html -->


<select id="city">
    <option value="select">CITY</option>
    <option value="beaches">Noida</option>
    <option value="museums">Mahrastra</option>
    <option value="mountains">Delhi</option>
</select>
<select id="state">
    <option value="select">STATE</option>
    <option value="chill">UP</option>
    <option value="fast-paced">Mahrastra</option>
    <option value="both">Delhi</option>
</select>


 <div class="result" data-city="beaches" data-state="chill" data-pincode="glenchill">glen gallery one</div>
 <div class="result" data-city="beaches">no gallery</div>
<div class="result" data-city="beaches" data-state="fast-paced" data-pincode="glenfast-paced">glen gallery two</div>
<div class="result" data-city="beaches" data-state="both" data-pincode="glenboth">glen gallery two</div>
<div class="result" data-city="beaches" data-state="glenchill">beaches and chill glenn</div>
<div class="result" data-city="beaches" data-state="glenfast-paced">beaches and fast-paced glenn</div>
<div class="result" data-city="beaches" data-state="glenboth">beaches and both glenn</div>
<div class="result" data-city="museums" data-state="chill">museums and chill</div>
<div class="result" data-city="museums" data-state="fast-paced">museums and fast-paced</div>
<div class="result" data-city="museums" data-state="both">museums and both</div>
<div class="result" data-city="mountains" data-state="chill">mountains and chill</div>
<div class="result" data-city="mountains" data-state="fast-paced">mountains and fast-paced</div>
<div class="result" data-city="mountains" data-state="both">mountains and both</div>  

`

Is there a way to render a React component *UI* into Django without calling APIs?

I’ve been working on my Django App for a couple of months now and decided to use React as my front-end, which I know is bad habit for development and makes everything a lot more complicated. I run npm build for my front-end app with Django, but when I launch the Django Project, it shows me the Django Rest Apis. When I wanted it to show me my UI, I built in React. Everything in my Django settings should be correct from tutorials and documentations, so I believe that isn’t the issue. I’ve tried calling the my API’s but I believe that isn’t the issue either.

I am trying to keep everything as simple as possible, so if I’m missing stuff in my code I apologize, I just want to understand the very basics of React without having a lot of side code.

Here is my App.js

import React from 'react';
import './App.css';
import Form from './Form';



class App extends React.Component {
  render(){
    return(
        <Form />
      )
  }
}



export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

retrieve json data, but it says object undefined [duplicate]

I am trying javascript to print out json data.
https://devsheet.com/code-snippet/editorjs-blocks-json-to-html-javascript/
I have tried this sample code but undefined problem occurs.

obj = '{"header":"John", "paragraph":30, "list":"New York"}';

html = '';
Object.keys(obj).forEach(function(block, index) {
        console.log(block['type']); // it prints undefined, it is expected to print keys (header, paragraph, etc.)
        switch (block['type']) {
        
        case 'paragraph':
            html += '<p>'+ block['data']['text'] +'</p>';
            break;
        
        case 'header':
            html += '<h'+ block['data']['level'] +'>'+ block['data']['text'] +'</h'+ block['data']['level'] +'>';
            break;
        ...
        ...

console.log(block[‘type’]); <—- it prints undefined, it is expected to print keys (header, paragraph, etc.)
How can I solve it?

Not getting data from jquery in codeigniter controller

500Getting Error like 500 (Internal Server Error)

jquery-3.6.0.js:10109 POST http://localhost/Banner_module/public/index.php/delete 500 (Internal Server Error)

HTML code:

  • <td><button type="button" value="<?= $row['bid'];?>" class="cd btn btn-outline-danger">Delete</button></td>

jquery Code:

$.ajax({
          type: "POST",
          url: "<?= site_url('delete') ?>",
           data: {"bid": bid}
         })

Routes :

$routes->post('delete','Home::delete');

controller:

public function delete(){

    

$user = new Bmodel();

    //$bid = $this->input->post('uid',true);
    $bid = $this->input->post('bid');
 
    // $data = array(
    //     'uid'  => $this->input->post('uid')
    //     );
    // $uid= json_encode($data);

    $data['user'] = $user->where('bid', $bid)->delete($bid);
   
    $response = ['status'=> "Deleted", 'status_text'=>'Deleted','status_icon'=>'success'];
    return $this->response->setJSON($response);
       }

Automate layer publishing in Geoserver

I have my shapefiles stored in the PostGIS table. now, I need to automate the process of publishing these tables on GeoServer. the overall process is that I am getting geojson from a remote server and storing it in the PostgreSQL database. this is being done using HTML, javascript, and PHP on button click event. now I want to create another functionality to publish newly added tables on GeoServer. I have created a workspace and data store in GeoServer and a bat file to publish these tables. but I want to do it on a button click event. Is there a way to execute the bat file in JavaScript? or any other workaround for the whole functionality?

the curl (.bat file) I am using is (http://www.snippetbymatt.com/2017/03/publish-postgis-layers-in-geoserver.html):

for /f %%a in (<list of tables you want to publish>.txt) do  curl -v
 -u <username>:<password>  -XPOST -H "Content-type: text/xml" -d "<featureType><name>%%a</name></featureType>"
 http://localhost:8080/geoserver/rest/workspaces/<name of
 workspace>/datastores/<name of store>/featuretypes pause

how to add cells to specific column in html

i added into table using .append in jquery and i need to add last colum with its cells

OR i need to add linkes into “PDF Files Link” column

<table class="table">
  <thead>
    <tr>

      <th scope="col">thumbnails</th>
      <th scope="col">Title</th>
      <th scope="col">authr</th>
      <th scope="col">PDF Files link</th>
    </tr>
  </thead>
  <tbody id="employee_table">

    </tr>
  </tbody>
</table>

and this my jquery code

    var videode='<tr><td><div class="video vidEle" style="width:42%;height:108px;" data-id="'+vid_id+'" ><a href="#top"><img class="v-img" style="width:79%;height:92px;" src="'+vid_thumb+'"/><i class="play-btn fa fa-play" style"top:72% !important"></i></a></div></td><td><div class=""data-id="'+vid_id+'" ><a href="#top"><div class="v-title">'+vid_title+'</div></a></div></td><td><p>'+channelTitle+'</p></td></tr>'
$('#employee_table').append(videode);

finally need to add linkes into “PDF Files Link” column

how can I hide parent div if all the children are “display:none”

I have this HTML block

 <div class="abc">
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
    </div>
    <div class="abc">
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: none;">xyz</div>
       <div class="xyz" style="display: block;">xyz</div>
       <div class="xyz" style="display: block;">xyz</div>
     </div>

I want to hide all the parent div if it contains all the “display:none” div else I want to show parent div..

Page Auto Reloads, When I Write/Append File on Websocket

Whenever i try to run this code. All works fine, Writing is done correctly in the file as well, but everytime append runs, the page reloads for some reason…. any way to stop that reload? I have tried Using SetTimeout… But that just delays reloading. does not acutally stop the reload error…. This is my first question here as well. Any Help would be appreciated

//server side JS -----------------------------------

const http = require('http').createServer();
const fs = require('fs');

const io = require('socket.io')(http, {
    cors: { origin : "*" }
});


io.on('connection', socket => {

    console.log('A User Connected!');

    socket.on('message', message => {

        console.log(message);
        let display = `${socket.id.substr(0,2)} Says:  ${message}`;
        io.emit('message', display);

        display += 'n';
        fs.appendFileSync('data.txt', display);
          

    });

});


http.listen(8080, () => console.log('listening on http://localhost:8080 ') );

//Client-side Js -----------------------------------

const socket = io('ws://localhost:8080');

socket.on('message', text => {

    const el = document.createElement('li');
    el.innerHTML = text;
    el.style.marginLeft = '500px';
    document.querySelector('ul').append(el);
    
});

document.getElementById('btn').onclick = () => {


    if(document.querySelector('input').value != ''){
        const text = document.querySelector('input').value;
        socket.emit('message', text);
        document.querySelector('input').value = '';

    }

}
document.addEventListener('keydown', (e) => {
    
    if(e.key === 'Enter' && document.querySelector('input').value != ''){
        const text = document.querySelector('input').value;
        socket.emit('message', text);
        document.querySelector('input').value = '';

    }

});
<!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>Web Sockets Testings!</title>
    <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
    <script defer src="app.js"></script>
</head>
<body>
    
    <input placeholder="message!">
    <button id="btn" onsubmit="return myFunction();">Send!</button>


    <ul>
    </ul>


</body>
</html>

ns, the page refreshes… Any Fixes..?

React – how to update the value using useState dynamically

Current UI:
enter image description here

There are 2 ways of updating the value of currentPercentage.

1.Scrolling
2.Click the button to update the percentage

For (1), I use react-scroll-percentage library to get the percentage.
For (2), I create 2 buttons to update the value of currentPercentage

I want to set the percentage of currentPercentage dynamically but I can’t find a way to handle it.

App.js

import "./styles.css";
import { useScrollPercentage } from "react-scroll-percentage";
import { useState } from "react";

export default function App() {
  const [ref, percentage] = useScrollPercentage({
    threshold: 0
  });

  // how to set the value of currentPercentage to percentage, while I can change the percentage by button
  const [currentPercentage, setCurrentPercentage] = useState(0);

  const onBtnClick = (num) => {
    setCurrentPercentage(num);
  };

  return (
    <div className="App" ref={ref}>
      <button
        onClick={() => {
          onBtnClick(50);
        }}
      >
        Change to 50%
      </button>
      <button
        onClick={() => {
          onBtnClick(100);
        }}
      >
        Change to 100%
      </button>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
      <h2>{`Percentage scrolled: ${percentage.toPrecision(2) * 100}%.`}</h2>
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/still-brook-hqb92?file=/src/App.js:0-2242

How to replace Mapbox default popup with customized information

I am kind of new to ReactJS and am working on a project that displays markers at different points, with the data being received from a JSON file. Currently, I am using popups to display information when the marker is being clicked on, as shown:

//Map.js
geoJson.features.forEach((location, i) => {
      const el = document.createElement("div");
      el.className = "marker";
      var marker = new mapboxgl.Marker(el)
        .setLngLat(location.geometry.coordinates)
        .setPopup(
          new mapboxgl.Popup({ offset: 0, className: "popup" }).setHTML(`
            <div>
              <h1>${location.properties.title}</h1>
              <p>${location.properties.description}</p>
              <a class="popupbutton" target="_blank" href=${location.properties.link}>
                <button class="popupbutton">Website Link</button>
              </a>
            </div>
          `)
        )
        .addTo(map);
      marker.getElement().addEventListener("click", () => {
        zoomIn(i);
      });
    });

As shown above, the popup is currently displaying the title and description of each marker, provided by the data in the JSON file. However, I would like to use something more modern and versatile to display this information, such as a Grommet Card (https://v2.grommet.io/card), since the current Mapbox Popup is not very appealing. How would I go about doing this?

How to know Swiper.js is not moving? (velocity = 0)

I’m using Swiper.js in my React project. It’s in swipeable free mode with autoplay. I will stop the autoplay when touchstart event is triggered, and resume the autoplay after touchend.

However, it’ll be awkward if the autoplay resumes immediately after the user release their finger since there’s still momentum velocity caused by the swipe. I wonder if there’s a way to detect the swiper stops, i.e. the velocity equals zero. I think the proper timing to resume autoplay is after the swiper stops for a while.

The following is my current workaround, wait 1 second until resuming the autoplay: (I also purposely slow down the momentum effect)

import React, { useRef, useState, useEffect } from "react";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";
import "swiper/css/bundle";
import "swiper/css/free-mode"
import "swiper/css/pagination"
import "./App.css";

// import Swiper core and required modules
import SwiperCore, {
  Autoplay,
  FreeMode, Pagination
} from 'swiper';

// install Swiper modules
SwiperCore.use([FreeMode, Autoplay, Pagination]);

export default function App() {

  const swiperRef = useRef(null);
  let disableAutoPlayTimer = null;

  useEffect(() => {
    const swiper = swiperRef.current;
    // subscribe event
    swiper.addEventListener("touchstart", touchStartHandler);
    swiper.addEventListener("touchend", touchEndHandler);
    return () => {
      // unsubscribe event
      swiper.removeEventListener("touchstart", touchStartHandler);
      swiper.removeEventListener("touchend", touchEndHandler);
    };
  }, []);

  const touchStartHandler = (e) => {
    swiperRef.current.swiper.autoplay.stop();
  }

  const touchEndHandler = (e) => {
    // I'm now using a timer to wait 1 second for the swiper to stop
    if (!disableAutoPlayTimer) {
      disableAutoPlayTimer = setTimeout(() => {
        swiperRef.current.swiper.autoplay.start();
        disableAutoPlayTimer = null;
      }, 1000);
    }
  }

  return (
    <>
      <Swiper
        dir="rtl"
        slidesPerView="auto"
        spaceBetween={30}
        freeMode={{
          enabled: true,
          momentumVelocityRatio: 0.5
        }}
        loop={true}
        loopedSlides={9}
        grabCursor={true}
        autoplay={{
          "delay": 0,
          "disableOnInteraction": false
        }}
        speed={1000}
        className="mySwiper"
        ref={swiperRef}
      >
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide><span style={{color: 'red'}}>Slide 3</span></SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
        <SwiperSlide>Slide 5</SwiperSlide>
        <SwiperSlide>Slide 6</SwiperSlide>
        <SwiperSlide>Slide 7</SwiperSlide>
        <SwiperSlide>Slide 8</SwiperSlide>
        <SwiperSlide>Slide 9</SwiperSlide>
      </Swiper>
    </>
  )
}

All in all, my question is, “How to know the current velocity of Swiper.js?”, or “How do I know the swiper is not moving?”
Any idea?

focus on an input that is located inside another component in vuejs?

I would like to be able to focus on input field when certain keys are entered. The input I would like to focus on exists inside autocomplete-vue.
This is where I call it:

<autocomplete v-shortkey="['alt', 's']"
              @shortkey.native="theAction()"
              ref="autocompleteInput" 
></autocomplete>

theAction method which I would like to allow me to focus on the input, looks like this:

theAction () {
      this.$refs.autocompleteInput.$el.focus()
    }

this focus on the whole section which is not what I want. the input exists 2 divs inside the what theAction focuses on. For bettere perspective, this is what this.$refs.autocompleteInput.$el returns :

<div>
  <div data-position="below" class="autocomplete"> 
     <input role="combobox" class="autocomplete-input"> 
  </div>
</div>

Any ideas on how I can focus on the input with class autocomplete-input? any suggestion is helpful!

Fast API ‘422 Unprocessable Entity’ on multiple file post with Axios

Getting ‘422 Unprocessable Entity’ trying to post a list of files to a FastAPI route.

Python:

@app.post("/upload-images/")
async def images(images: List[UploadFile] = File(...)):
    
    for image in images:
        print(image.filename)

Javascript:

    async function handleUpload() {
    if (files.length > 0) {
      const formData = new FormData();

      Array.from(files).forEach((f) => {
        formData.append("images[]", f);
      });

      console.log(formData.getAll("images[]")); //can see the images appended properly
      const imageUploadResponse = await axios
        .post("/upload-images/", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          // toast.error("Woops. Image upload failed.");
        });
    }
  }

I’ve also tried just appending the array with no luck:

formData.append("images", files);

Can someone please let me know what I am doing wrong?