RegEx to stop user from entering negative values and special characters in input

<input class="input" pInputText   [disabled]="disabled" [(ngModel)]="data.input.value"
(change)="inputOnChanges()" (keypress)="keyPress($event)" >

.ts file

const pattern = /^[+]?([0-9]+(?:[.][0-9]*)?|.[0-9]+)$/;
console.log('event is::',event);
const inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {    
    // invalid character, prevent input
    event.preventDefault();
}

I am using above regex. Also, it says charCode is deprecated.

Sit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnis

Sit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnisSit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnisSit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnisSit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnisSit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnisSit excepturi est voluptatibus ut amet aut tenetur excepturi id sit ut quia molestiae reiciendis qui soluta et omnis

How can I use await for react-query data?

I should call an API then use it’s data as parameter for another request:

const { data, isLoading, error } = useQuery('fetchAvailableProducst', fetcher, { enabled: false });

const sendOrder = (categoryID) => {
  const availableProducst = /* function to fetch a list of category */
  const ids = [];
  availableProducst.map(item => {
    ids.push(item.id);
  });
  sendOrderMutation.mutate(ids);
}

the above code doesn’t work, I just written for mentioning to an idea… Actually I’m looking for a way to add something like await before availableProducst (which comes by useQuery()) to get list then fill ids and then call sendOrderMutation to send order…

But is there any way to use await for useQuery() data?

How do I use user input from a textbox as parameters to display information on a different HTML page?

I have 2 pages, index.html, and tracklist.html. For my webpage, I want to get an artist’s name and an album name from 2 text boxes on index.html, use those as the parameters for my getAlbumTracks() function, and display the array of tracks on tracklist.html after clicking a search button (button is on index.html).

Below I have my index.html, tracklist.html, and app.js, and as of right now, when I run getAlbumTracks() in the console on tracklist.html with manually inputted parameters, I am able to display the array on the page, like this: https://gyazo.com/af94a5c5966d9c1cbaea74369a35add2 but don’t know how to do it with user input from textboxes on a different page. I’m a bit new to javascript so any help is appreciated, thanks!

index.html:

<!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>Rank It</title>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>
  <body>
    <form action="tracklist.html">
      <div>
        <div>
          <div class="search">
            <input
              type="text"
              id="album"
              class="searchbar"
              placeholder="Album Name"
            />
          </div>
        </div>

        <br /><br />

        <div>
          <div class="search">
            <input
              type="text"
              id="artist"
              class="searchbar"
              placeholder="Artist's Name"
            />
          </div>
        </div>

        <br /><br />

        <div>
          <div class="search">
            <input type="submit" value="Click" onclick="display" />
          </div>
        </div>
      </div>
    </form>
  </body>
</html>

tracklist.html

<!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" />
    <link rel="stylesheet" href="style2.css" />
    <script src="app.js"></script>
    <title>Rank It</title>
  </head>
  <body>
    <div class="tracklist">
      <div id="arrPrint"></div>
    </div>
  </body>
</html>

app.js:

async function getAlbumTracks(AlbumName, ArtistName) {
  
  //API that gets json file of album information given artist's name and album name
  const response = await fetch("https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=d94b7d68284cbab1cdb7c2c3c81fd913&artist="
  + ArtistName + "&album=" + AlbumName + "&format=json")
  const data = await response.json();

  //Declaring numberOfTracks and TrackList array
  const numberOfTracks = data.album.tracks.track.length;
  const TrackList = [];
  
  //For Loop that gets each song name and puts them in TrackList[]
  for (let i = 0; i < numberOfTracks; i++) {
    TrackList[i] = data.album.tracks.track[i].name;
  }
  
  //All the code below is used to display the tracks with numbers on the webpage
  let arrPrint = document.getElementById("arrPrint");
  let list = "<ol>";

  for (let i = 0; i < numberOfTracks; i++) {
    list += "<li>" + TrackList[i] + "</li>";
  }

  arrPrint.innerHTML = list;
}

//Function that is supposed to take user input and call the getAlbumTracks function but it doesn't work
function displayAlbumTracks() {
  let Album = String(document.getElementById("album").value);
  let Artist = String(document.getElementById("artist").value);
  getAlbumTracks(Album, Artist);
}

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

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 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..