Sort() in JavaScript

Hello friends

  • how to arrange a number string with several characters?
  • I converted to a number, but it only gives me one 2
     <input type="text" name="numbers" id="numbers" readonly value="2, 4, 14, 10, 90, 23, 16"/>
    
     <button type="button" id="run">Lancer le script</button>
    

Run the script

(() => {
// to get the value of an input: document.getElementById("element-id").value

document.getElementById("run").addEventListener("click", () => {
   
   
});

})();

Handle API to not receive value less than 0 (negative values)

I need to treat the API result so that I don’t receive values less than 0, I’ve been trying this way and so far I haven’t been able to:

private handleChart(data: Object): void {
    const series = [];

    for (const [key, value] of Object.entries(data)) {
      series.push({
        name: key,
        data: value,
        type: "line",
      });
    }
    
    if (series[0].data.length < 0) {
      delete series[0].data;
    }
    console.log(data );  

    this.plotChart(series);
  }

Original code:

private handleChart(data: Object): void {
    const series = [];

    for (const [key, value] of Object.entries(data)) {
      series.push({
        name: key,
        data: value,
        type: "line",
      });
    }

    this.plotChart(series);
  }

How do I show one of the divs sequentially when the page is refreshed?

How do I show one of the divs sequentially when the page is refreshed? for example, div 1 will appear when the page is opened, and when the page is refreshed, div 2 will change to 3 – 4 -5 on the next refresh, and when the queue is finished, it will return to the beginning.

example i’m working on :

     <style>
            .category {
                display: none;
            }
        </style>
        <div class="category">1</div>
        <div class="category">2</div>
        <div class="category">3</div>
        <div class="category">4</div>
        <div class="category">5</div>
    <script>
     $(document).ready(function () {
                let divs = document.querySelectorAll(".category");
                console.log(divs.length);
                for (let index = 0; index < divs.length; index++) {
                    $(divs[index]).show()
                }
            });
</script>

but here it shows all when the page is loaded. How can I solve this?

How to ensure onblur event before ontouchstart

Our in-house web app uses onblur to capture user input and onmouseup to act on it. We had problems with the onblur event not always triggering before onclick, so I changed that to onmouseup (although, it would seem that onclick can be combined with onfocus to ensure the onblur).

When rendering our web content on a tablet we use ontouchstart which works well, but none of the techniques I used to ensure the onblur trigger before the onmouseup work. I can fix the problem by adding the onblur script as part of the onmouseup, but I’d prefer not to, since the click is for a generic ‘Save’ action.

This code snippet works well with any of Chrome’s simulated touch enabled devices.
If ‘Click me’ is touched right after a string input, the console log output is…

  1. focus
  2. ontouchstart
  3. onblur

Thanks for any suggesions.

<html>
<body>
    <div>
        <input id="input" onblur="
            console.log('onblur');
            document.getElementById('output').innerHTML = document.getElementById('input').value">
        </id>
        <div id="output">No Data</div>
        <div id="click" ontouchstart="
            document.getElementById('output').focus(console.log('focus'));
            console.log('ontouchstart'); 
            document.getElementById('output').innerHTML = 'ontouchstart' ">
            Click me
        </div>
    </div>
</body>
</html>

Can i use a NodeJS server with Webtorrent, as a link between normal TCP/UDP peers and WebRTC peers? [closed]

Webtorrent
Webtorrent-hybrid

WebTorrent is a streaming torrent client for node.js and the browser. In the browser, WebTorrent uses WebRTC (data channels) for peer-to-peer transport, but nodejs uses UDP/TCP peers (or even both WebRTC and UDP/TCP).

My question is if it’s possible to make a nodejs app that proxies the packages that receives from UDP/TCP peers to WebRTC peers.
I don’t want the nodejs app to download the whole torrent and then seed it to the WebRTC peers,
i want to somehow forward the UDP/TCP packages to the WebRTC peers.

Javascript dropdown and switcher buttons next prev

I need choose from dropdown menu one of class, and put it to id=”get”
The switcher work perfectly, thanks to Mister Jojo (Javascript show next prev content appenchild)

my question is,

  1. is here more compact, lightly solution than I made with functions in dropdown

  2. when I choose from dropdown menu and click to next or prev button, it does not work immediately, only when I click second time

Many Thanks

function tog() {document.getElementById("ts").classList.toggle("show");}

window.onclick = function(event) {
 if (!event.target.matches('.dropbtn')) {
    var dr = document.getElementsByClassName("ts");
    var i;
    for (i = 0; i < dr.length; i++) {
      var odr = dr[i];
      if (odr.classList.contains('show')) {
        odr.classList.remove('show');
      }
    }
  }
  }
  

const
  dGet   = document.getElementById('get')
, dBack  = document.getElementById('back')
, slides = document.querySelectorAll('.mySlides')
, current = 
  { slide : null
  , index : 0
  , len   : slides.length
  }; 

 
plusDivs(0);

function plusDivs(n)
  {
    // more easy with a modulo...
  current.index = (current.index +n +current.len) % current.len;
  
  if (current.slide) dBack.appendChild( current.slide )
  
  current.slide = dGet.appendChild( slides[current.index] )
  }

function f1() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  var three = document.getElementById("three");
  var back = document.getElementById("back");
  
  document.getElementById("get").appendChild(one);
back.appendChild(two);
  back.appendChild(three);
}

function f2() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  var three = document.getElementById("three");
  var back = document.getElementById("back");
  
  document.getElementById("get").appendChild(two);
back.appendChild(one);
  back.appendChild(three); }

function f3() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  var three = document.getElementById("three");
  var back = document.getElementById("back");
  
  document.getElementById("get").appendChild(three);
back.appendChild(one);
  back.appendChild(two); }
#get {
  height   : 300px;
  width    : 500px;
  border   : 1px solid red;
  left     : 100px;
  position : absolute;
  }
#back {
  display : none;
  }
.ts > a.tAr {display:block!important;background-image: linear-gradient(#3d00974a, transparent);}
.teletab {
  float:left;
  min-width: 160px;
  overflow: auto;
  z-index: 1;
    position: absolute;
    background: #1b092d;
    max-height: 400px;
overflow-x: hidden;
width: 216px;
}
.teletab a {
  padding: 4px 16px;
  display: none;
  width: 200px;
max-height:40px;
border-style: solid;
border-width: 1px 0 0 0;
color: #2aa;
}
.show a {display: block!important;}
<div class="teletab ts" id="ts">
<a onclick="f1()">first</a>
<a onclick="f2()">second</a>
<a onclick="f3()">third</a>
</div>
<button onclick="tog()" class="dropbtn ddb">
▽
</button>
<button onclick="plusDivs(-1)"><</button>
<button onclick="plusDivs(1)">></button>
<div id="back">
  <div id="one" class="mySlides">
    <span class="Tx1">111</span>
  </div>
  <div id="two" class="mySlides">
    <span class="Tx1">222</span>
  </div>
  <div id="three" class="mySlides">
    <span class="Tx1">333</span>
  </div>
</div>
<div id="get"></div>

Update a dynamic dropdown with Javascript in HTML

This webpage has two dropdown options, which seem to hold the text in innertext/innerHTML. However if you update the innertext it can change the text shown on the webpage but does not really update the field which then causes the rest of the page to load. I was wondering how to update this field. See innertext on line 6.

<div class="av-select is-untouched av-valid css-b62m3t-container" id="orgSelect">
    <span id="react-select-2-live-region" class="css-7pg0cj-a11yText"/>
    <span aria-live="polite" aria-atomic="false" aria-relevant="additions text" class="css-7pg0cj-a11yText"/>
    <div class="organization-select__control css-1nhojdd-control">
        <div class="organization-select__value-container organization-select__value-container--has-value css-13y5847">
            <div class="organization-select__single-value css-1dc049i-singleValue">Text to Update</div>
            <div class="organization-select__input-container css-1azzn7d" data-value="">
                <input class="organization-select__input" autocapitalize="none" autocomplete="off" autocorrect="off" id="organization" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" aria-expanded="false" aria-haspopup="true" aria-controls="react-select-2-listbox" aria-owns="react-select-2-listbox" aria-errormessage="" role="combobox" value="" style="color: inherit; background: 0px center; opacity: 0; width: 100%; grid-area: 1 / 2 / auto / auto; font: inherit; min-width: 2px; border: 0px; margin: 0px; outline: 0px; padding: 0px;"/>
            </div>
            <div class="organization-select__indicators css-1wy0on6">
                <span class="organization-select__indicator-separator css-1okebmr-indicatorSeparator"/>
                <div class="organization-select__indicator organization-select__dropdown-indicator css-fkilnp-indicatorContainer" aria-hidden="true">
                    <svg height="20" width="20" viewBox="0 0 20 20" aria-hidden="true" focusable="false" class="css-8mmkcg">
                        <path d="M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"/>
                    </svg>
                    <span class="sr-only">Toggle Select Options</span>
                </div>
            </div>
        </div>
        <input name="organization" type="hidden" value="[object Object]"/>

This is one of the things I have tried so far, the other field to update looks exactly the same just has a data-value field included:

var dataContainer = document.getElementsByClassName('payer-select__single-value css-1dc049i-singleValue')[0];
var dataValue = parseInt(dataContainer.getAttribute('data-value'));
dataContainer.setAttribute('data-value', "updated value");
dataContainer.innerHTML = "updated value"

Replace text on webpage using script with Tampermonkey

I want to replace spices name in pages like this one: https://www.inaturalist.org/observations?locale=en&place_id=97391&preferred_place_id=8860&taxon_id=61902&view=species

So I want to replace for example ‘Chrysolina fastuosa’ to something different with this code:

var replaceArry = [
    [/Chrysolina fastuosa/gi,    'Złotka jasnotowa'],

    
];
var numTerms    = replaceArry.length;
var txtWalker   = document.createTreeWalker (
    document.body,
    NodeFilter.SHOW_TEXT,
    {   acceptNode: function (node) {
            
            if (node.nodeValue.trim() )
                return NodeFilter.FILTER_ACCEPT;

            return NodeFilter.FILTER_SKIP;
        }
    },
    false
);
var txtNode     = null;

while (txtNode  = txtWalker.nextNode () ) {
    var oldTxt  = txtNode.nodeValue;

    for (var J  = 0;  J < numTerms;  J++) {
        oldTxt  = oldTxt.replace (replaceArry[J][0], replaceArry[J][1]);
    }
    txtNode.nodeValue = oldTxt;
}

But that code don’t work on this page. This code works perfectly on headers, plain text, but not where I need it. What I need to change to make it work?

TypeError: Cannot read properties of null (reading ‘save’)

I am coding a premium system for my bot and it worked for like 1 day. Now I am getting this error. I hope somebody can help me! It would be really cool! https://imgur.com/a/NVfjB7l
This is my error message. I tried to solve it for 2 days but never find an answere. Hopefully you can.

Here is my code:

const { Command } = require("reconlx");
const moment = require("moment");
const schema = require("../../Models/code.js");
const User = require("../../Models/User");




module.exports = new Command({
  // options
  name: "redeem",
  description: `redeem preium code`,
  userPermissions: ["ADMINISTRATOR"],
  category: "Premium",
  options: [
    {
      name: "code",
      description: `give me code`,
      type: "STRING",
      required: true,
    },
  ],
  // command start
  run: async (  client, interaction, args ) => {
    // Code
    // Check if the user with a unique ID is in our database.
    let user = await User.findOne({ Id: interaction.member.id });

    // Check Users input for a valid code. Like `!redeem ABCD-EFGH-IJKL`
    let code = interaction.options.getString("code");

    // Return an error if the User does not include any Premium Code
    if (!code) {
      interaction.followUp(`**Please specify the code you want to redeem!**`);
    }

    // If the user is already a premium user, we dont want to save that so we return it.
    if (user && user.isPremium) {
      return interaction.followUp(`**> You already are a premium user**`);
    }

    // Check if the code is valid within the database
    const premium = await schema.findOne({
      code: code.toUpperCase(),
    });

    // Set the expire date for the premium code
    if (premium) {
      const expires = moment(premium.expiresAt).format(
        "dddd, MMMM Do YYYY HH:mm:ss"
      );

      // Once the code is expired, we delete it from the database and from the users profile
      if (moment().isAfter(premium.expiresAt)) {
        premium.remove();
        user.isPremium = false;
        User.save();
        return interaction.followUp(
          `**> The code you have entered is expired!**`
        );
      }

      // Save the User within the Database
      user = await user.save({ new: true }).catch(() => {});
      client.userSettings.set(interaction.member.id, user);
      await premium.deleteOne().catch(() => {});

      // Send a success message once redeemed
      interaction.followUp(
        `**You have successfully redeemed premium!**nn`Expires at: ${expires}``
      );

      // Error message if the code is not valid.
    } else {
      return interaction.followUp(
        `**The code is invalid. Please try again using valid one!**`
      );
    }
  },
});

It was running for 1 Day. Idk how lol. But after I woke up and wanted to redeem a code. It says the error.

Maybe one of you knows why.

Object, object Problem | Using country – city json file compatible with PrimeReact

I am trying to embed country – city json file with PrimeReact. I am having difficulty because of this.
I’m pulling the information for the country, but the city shows as [Object, object ].

 <AutoComplete
              placeholder="Search Country"
              dropdown
              value={selectedCountryValue}
              id="dd"
              completeMethod={searchCountry}
              onChange={(e) => setSelectedCountryValue(e.value)}
              suggestions={autoFilteredValue}
              field="name"
              style={{ marginLeft: 10, height: 40, width: 267 }}
            />
 <AutoComplete
              placeholder="Search City"
              dropdown
              value={selectedCountryValue}
              id="dd"
              completeMethod={searchCity(selectedCountryValue)}
              onChange={(e) => setSelectedCountryValue(e.value)}
              suggestions={selectedAutoValueCity}
              field="states"
              style={{ marginLeft: 10, height: 40, width: 267 }}
            />

I used variables. When I select the country, the json other data comes. Console.log also works flawlessly

const searchCity = (event) => {
    setTimeout(() => {
      if (event) {
        console.log("here");
        console.log(event.states.map((obj) => obj.name));
        return event.states.map((obj) => obj.name);
      }
    }, 250);
  };

The Json data sequence is also as shown below.


"data" :[
    {
      "code2": "AF",
      "code3": "AFG",
      "name": "Afghanistan",
      "capital": "Kabul",
      "region": "Asia",
      "subregion": "Southern Asia",
      "states": [
        {
          "code": "BDS",
          "name": "Badakhshān",
          "subdivision": null
        },

How to adapt JSON.Parser for NaN in Javascript?

I’m trying to adapt JSON.Parse() for NaN.

console.log(JSON.parse('{"n": 1}'));
console.log(JSON.parse('{"n": NaN}'));

1st one is {n:1}.

2nd one has an error which says Unexpected token N in JSON.
And I want to change NaN to 0 like {n: 0}.

I found a resource which create JSON Parser from scratch.https://lihautan.com/json-parser-with-javascript/#implementing-the-parser

It’s good he separates keys and values so that I can check only values if there is NaN and fix it.
But the problem is I have no idea where I can put the NaNParser() and the process. Because the parameter looks coming 1 by 1 character.

If you could give me some advice, it really helps me.
https://codesandbox.io/s/json-parser-with-error-handling-hjwxk?from-embed