JavaScript – Using localStorage to save numbers: how to extract numbers from localStorage

So i have made a web based program and I am using localStorage to save my variables. However I’m running into an issue where i cant get back the numbers from localStorage (as they are a string when saved) is there a way to set the strings back to a number without effecting the rest of the code?

let cardCount = 0;
let card = 0
function DisplayCardCount() {
  cardCount++;
  card++;
  document.getElementById("DisplayCountCard").innerHTML = cardCount;
}

//Counting the cash
let cashCount = 0;
let cash = 0
function DisplayCashCount(){
  //Display Session
  cashCount++;
  //Saving Data to local
  cash++;
  document.getElementById("DisplayCountCash").innerHTML = cashCount;
}

//Get Sell Total Price
let SellTotal = 0;
function DisplaySellTotal(){
  SellTotal++;
  document.getElementById("DisplaySellTotal").innerHTML = SellTotal*5;
  return SellTotal;
}
//Clear all variables (set all varables back to 0)
function Clear(){
  SellTotal = 0;
  cashCount = 0;
  cardCount = 0;
  document.getElementById("DisplayCountCard").innerHTML = 0;
  document.getElementById("DisplayCountCash").innerHTML = 0;
  document.getElementById("DisplaySellTotal").innerHTML = 0;
}
//Save the payment information


let totalSales = 0
let totalCard = 0
let totalCash = 0
let totalSalesCount = 0

function takePayment(){
  //Count the ammount of times Confirm has been pressed
  let Counting = totalSales+=1;
  //Save Array to local Storage
  const SalesArray = [card, cash, Counting]
  localStorage.setItem('Sales',JSON.stringify(SalesArray));
  const SalesData = JSON.parse(localStorage.getItem('Sales'));
  console.log(SalesData);
  //Save Data to local storage for card and cash
  localStorage.setItem('card',JSON(card))
  localStorage.setItem('cash',JSON(cash))

  //Set clear all functions to start again (not effecting local storage)
  SellTotal = 0;
  cashCount = 0;
  cardCount = 0;
  document.getElementById("DisplayCountCard").innerHTML = 0;
  document.getElementById("DisplayCountCash").innerHTML = 0;
  document.getElementById("DisplaySellTotal").innerHTML = 0;
}

“ReferenceError: URL is not defined” from a Web assembly generated javascript file

I’m getting a “ReferenceError: URL is not defined” when initializing a Web Assembly module. The error is for a line like the one below, in the web assembly generated javascript file.

wasmBinaryFile=new URL("some_filename.wasm")

I’m exporting the module from the wasm generated javascript file and using it in another javascript file by constructing the module like

Module().then(...)

Why does this error happen? How can I define the URL() constructor before it’s called so this error won’t happen.

The thing is this normally works – however, when I invoke the module construction inside an AudioWorkletNode constructor, the error happens. Somehow, the URL() constructor definition is being deleted.

How to use js-cookie?

This question probably has been answered but I cant seem to figure out how to implement js-cookie inside of my code. My goal is to have a csrf token for an ajax call or whatever its called (I’m sorta new) because the error I was getting was not having a csrf token. I’ve downloaded js-cookie with npm into my project but I’m not sure if I’m supposed to link it to the page with a script and src tag. And now I’m getting an error: “Uncaught TypeError: $.cookie is not a function” Any ideas?

Here is my html file (Just the body) which has the links to jquery and the javascript page :

<body>
...code...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="staticfiles/item-store.js"></script>
</body>

Here is my Javascript file :

//Creating CSRF Token
var csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

// Send info to Python File
function Send_Python_Info() {
  ToSend = JSON.stringify(item_mode)
  console.log(ToSend)
  window.alert(ToSend)
  $.ajax({
    url:"/test",
    type:"POST",
    contentType: "application/json",
    data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
    data: JSON.stringify(ToSend),
    success: function () {
      alert("Saved!");
    }
  });
}

Thanks for your time!

JavaScript prevent (mobile) keyboard to hide

I have this HTML which has editor and buttons above the keyboard:

------------
|1| Hello  |
|2| World  |
| |        |
| |        |
------------
|Tab|( ) [ |
------------
|qwertyuiop|
| asdfghkl |
| zxcvbnm  |
| [     ]  |
------------

My keyboard is showed when I clicked the editor.
If I click the button Tab while the keyboard is shown, the keyboard is hiding. I want to prevent the keyboard from hiding.

Like

keyboard.preventDefault();

Only displaying database rows that match the ID of the user that created it

I have a HTML table that’s displaying all of my database’s data (individual job listings). However, I need to write an if statement to only show a job if the job’s createdByUserID matches the ID of the user viewing it.

$(function() {
    var records = [];
    $.getJSON('https://db-ommitted-for-privacy?tableName=JobListings&fields=company,logo,img,companyDescription,role,roleDescription,location,link,createdByUserID,dateAdded&view=AllListings', function(data) {
        $.each(data.records, function parseJSON(i, { fields: f }) {
            var tblRow = "<tr>" + 
                "<td>" + 
                    "<div style='padding-top: 1%; padding-bottom: 1%;'>" + 
                        "<div style='border: 1px solid black;'>" + 
                            "<button class='accordionList' style='font-size: large; outline: none;'>" + 
                                "<span style='padding-top: 2.5%; padding-bottom: 3%;'>" + 
                                    "<img src='" + f.logo + "' height='30px'>" + 
                                "</span> &nbsp;<span style='padding-top: 3%; padding-bottom: 3%;'>&nbsp;&nbsp; " + 
                                    f.company + " &nbsp; | &nbsp; " + f.role + 
                                " &nbsp;&nbsp; <span style='color: #2b2b2b;''><span class='iconify-inline' data-icon='eva:pin-outline' style='color: #2b2b2b;'></span> " + f.location +"</span></span>" + 
                            "</button>" + 
                            "<div class='panel'>" + 
                                "<img src='img/jobBanner2.png' width='100%'>" +
                                "<br>" + 
                                "<p style='color: #505050;'>Posted: " + f.dateCreated + " &nbsp; | &nbsp; Status: " + f.status + "</p>" + 
                                "<h4>About this role:</h4>" + 
                                "<p>" + f.roleDescription + "</p>" + 
                                "<h4>About " + f.company + ":</h4>" + 
                                "<p>" + f.companyDescription + "</p>" + "<br>" + 
                                "<a href='pricing.html' class='button btn btn-lg btn-block btn-sm button-black' style='padding-top: 1%; padding-bottom: 1%; width: 200px;'>Apply &nbsp; <span class='iconify-inline' data-icon='bi:arrow-right-circle' data-width='15' style='color: white;'></span></a>" + 
                                "<br>" + "</div>" + 
                            "</div>" + 
                        "</div>" + 
                    "</div>" + 
                "</td>" + 
            "</tr>"
            $(tblRow).appendTo("#userdata tbody");
        });
    });
});

The code to display a logged in user’s ID:

<div data-ms-member="id"></div>

I understand the concept of how this should work, but I have no idea how to execute it in JS and HTML. Any help is appreciated, thanks.

Fuse.js wrong scoring system

I used Fuse.js to implement a search system to my discord bot. However when I give the search string “Paper Beauty (Awakened)”, It returns another Item that is similar to it as the first element in the array.

Results:

[
  {
    item: 'Paper Beauty (Winter)',
    refIndex: 77,
    score: 0.01857804455091699
  },
  {
    item: 'Paper Beauty (Awakened)',
    refIndex: 135,
    score: 0.01857804455091699
  },
  { item: 'Patternine', refIndex: 122, score: 0.4 },
  { item: 'Bright Reaper', refIndex: 31, score: 0.40657505381748826 }, 
  { item: 'Spade', refIndex: 112, score: 0.41000000000000003 },        
  { item: 'Puppet', refIndex: 61, score: 0.42000000000000004 },        
  { item: 'Expert Sorcerer', refIndex: 8, score: 0.5231863610884103 }, 
  { item: 'Water Goddess', refIndex: 13, score: 0.5231863610884103 },  
  { item: 'Water Bender', refIndex: 41, score: 0.5231863610884103 },   
  { item: 'Super Firework', refIndex: 176, score: 0.5231863610884103 },
  { item: 'Spider Boss', refIndex: 44, score: 0.5324001715007329 }     
]

Code:

const Fuse = require("fuse.js");
const { trendSystem, demandSystem } = require("../../util/functions");
const names = require("../../names.json");



module.exports = {
    name: "stats",
    category: "trading",
    devOnly: false,
    run: async ({ client, message, args }) => {
        const options = {
            includeScore: true,
        };
        const searcher = new Fuse(names, options);
        const results = searcher.search(args[0]).slice(0, 11)
        console.log(results)
    }
}

TensorFlow JS, Problem with Sequential Model

I keep getting this error:
Uncaught (in promise) TypeError: tf.layers.AveragePooling2D is not a function.
I don’t understand why I get this layer since I have imported tensorflow and tf.layers.maxPooling2D does not give any errors. Thanks for your help!

InnerHTML undefined JavaScript Meaning

So I am creating a website for myself and I am using JavaScript to create a decrypting animation. I keep getting the error innerHTML is undefined and I am having trouble figuring it out. The JavaScript code is:

function decrypt(){
    var name = document.getElementsByClassName("name")[0];
    var char = name.getElementsByClassName("chars");
    for (var i = 0, j = name.children.length; i <= j; i++) {
      var compareChar = char[i].innerHTML;
      if(compareChar != message[i]){
        let randomNum = Math.floor(Math.random() * message.length); 
        char[i].innerHTML = message[randomNum];
      }
      else {
        document.getElementsByClassName("chars")[i].style.borderColor = "black";
        document.getElementsByClassName("chars")[i].style.backgroundColor = "black";
        }
    }
}

The innerHTML part of the line: var compareChar = char[i].innerHTMLis giving me the innerHTML defined error. Any help would be appreciated, been stuck on this for a while now.

Best way to change navbar dropdown function from CSS-only to Javascript on mobile?

Here is my current CSS-only dropdown menu html:

        <div class="main-nav">
            <div class="main-nav-container">
                <div class="nav-links">
                    <ul>
                        <li class="nav-link"><a>Nav Link</a>
                            <div class="dropdown">
                                <ul class="dropdown-list-type">
                                    <li>
                                        <ul>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                        </ul>
                                    </li>                                
                                </ul>
                            </div>
                        </li>
                     
                        <li class="nav-link"><a>Nav Link</a>
                            <div class="dropdown">
                                <ul class="dropdown-list-type">
                                    <li>
                                        <ul>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                            <li>
                                                <a href="#">Option</a>
                                            </li>
                                        </ul>                                        
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

Relevant CSS:

.dropdown{
position: absolute;
display: flex;
top: 100%;
border-top: solid 1px var(--white-3);
left: 0;
z-index: 8;
opacity: 0;
pointer-events: none;
transition: .3s; }

.nav-link:hover > .dropdown,
.dropdown-link:hover > .dropdown{
    transform: translate(0, 0);
    opacity: 1;
    pointer-events: auto;
}

On mobile, I want the user to be able to open and close the dropdown by tapping on the “Nav Link”. Currently, the user can tap to open, but then has to tap somewhere else to close the dropdown. I figure I need Javascript make it do what I want.

My idea:

  • Use a media query to remove the hover function on mobile
  • Use Javascript to add a class to the “Nav Links” on mobile
  • Using this class, with JS, make the Nav Links toggle the dropdown to display/hide

Is this the best way to do it? If so, how do I add a class to the “Nav Links” with Javascript at a specific screen size?

I would like to just use plain Javascript, no Jquery.

Also, I current want to keep the CSS-only hover approach for desktop. So I want the Javascript function only for the mobile view.

I hope that makes sense to everyone. Thank you!

Hiding HTML elements working on Desktop and Mobile browsers but not in the Android Studio WebView

As a preface, I am not very experienced with web development and am working on this for a university assignment.

My HTML Code

<!DOCTYPE html>c
<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="app.css">
    </head>
    <body>
        <div class="container">
            <div id="categoriesList" class="flex-center flex-column">
                <h1>Welcome to EduQuiz</h1>
                <a class= "btn" data-cat="20">Mythology</a>
                <a class= "btn" data-cat="23">History</a>
                <a class= "btn" data-cat="9">General Knowledge</a>
                <a class= "btn" data-cat="12">Music</a>
                <a class= "btn" data-cat="17">Science</a>
                <a class= "btn" data-cat="27">Animals</a>
                <a class= "btn" data-cat="22">Geography</a>
                <a class= "btn" data-cat="18">Information Technology</a>
            </div>
            <div id="difficulty" class="hidden flex-center flex-column">
                <a class= "btn" data-difficulty="easy"> Easy</a>
                <a class= "btn" data-difficulty="medium">Medium </a>
                <a class= "btn" data-difficulty="hard">Hard</a>
            </div>
        </div>
        <script src="categories.js"></script>
    </body>
</html>

My JavaScript code

    const category = Array.from(document.getElementsByClassName("btn"));
const allCats = document.getElementById('categoriesList');
const difficulties = document.getElementById('difficulty');

localStorage.clear();

category.forEach((cat => {
    cat.addEventListener('click', (e) => {
        console.log(e.target);
        allCats.classList.add('hidden');
        difficulties.style.left = "8rem";
        difficulties.classList.remove("hidden");

        if (cat.getAttribute("data-cat") != null) {
            localStorage.setItem("cat", cat.getAttribute("data-cat"));
            // const selectedCategory= localStorage.getItem("cat");
            //console.log(selectedCategory);
        }

        if (cat.getAttribute("data-difficulty") != null) {
            localStorage.setItem("difficulty", cat.getAttribute("data-difficulty"));
            buildString();
        }
    });

}));


function buildString() {
    const selectedCategory = localStorage.getItem("cat");
    console.log(selectedCategory);
    let selectedDifficulty = localStorage.getItem("difficulty");
    console.log(selectedDifficulty);

    let url = "https://opentdb.com/api.php?amount=10&category=";
    url += selectedCategory;
    url += "&difficulty=";
    url += selectedDifficulty;
    url += "&type=multiple";
    console.log(url);

    sessionStorage.setItem("diff", selectedDifficulty);
    sessionStorage.setItem("url", url);

    window.location = "game.html";
}

Problem:
On mobile browsers and desktop browsers the code works as intended. When a category is chosen, it hides the category buttons and shows the difficulty buttons. However, in the webview component of Android studio, when a category is chosen, nothing happens.

How should I fix this?

Custom style of scollbar in jQuery

I am creating a Chrome Extension using jQuery, however I stuck at style the scrollbar style as
I tried to change .css of this panel element (resultDiv).

- List item

        resultDiv.css({
        "text-align": "left",
        "font-family": "'Segoe UI', sans-serif",
        "font-size": "9.8pt",
        "width": WIDTH_POPUP + "px",
        "max-height": "300px",
        "overflow": "auto",
        //"border": "0.285px solid #ffffff11",
        "padding": "5px",
        "margin": "5px",
        "border-radius": "1rem",
        "color": "#ffffff",
        "background": style_code[value],
        "position": "absolute",
        "top": y,
        "left": currentX + "px",
        "z-index": "99999999999999999",
        "opacity": "0.93"
    });

Is this a valid use case for derived state from props? [react]

React documentation seems to be very insistent on the idea that in almost every situation, deriving state from props is a bad idea, an anti-pattern, verbose, likely to cause bugs, hard to understand, and all-around probably going to place a curse on one’s lineage for a thousand years.

My use case isn’t that weird, so I’m probably doing something wrong, but the suggested patterns for not needing getDerivedStateFromProps() (i.e. making Your object fully controlled or fully uncontrolled) don’t seem like good solutions.

The situation: I have a Table component, that takes in an array rows as a prop. Table is used in many different places in my app. I want the Table to be able to handle row-sorting. It is obviously a bad idea to to make whichever parent component controls Table to have to control the sorting*, so fully controlled is out. Making Table fully uncontrolled with a key, also seems like it doesn’t make a lot of sense unless the key is the row-data itself– but my understanding is that key is meant to be simple data (like an id), and actually having to compare all of the rows, which are typically fairly complicated objects, would be pretty inefficient.

My current solution: Table has a state variable sortedRows which is updated either whenever sort() is called or whenever props.rows is updated (via getDerivedStateFromProps), by:

  1. Making a shallow copy of props.rows,
  2. in-place sorting that copy and
  3. updating state.sortedRows on that value.

As I see it, there is still only one source of truth here (which is from props), and the state is always just storing a sorted version of that truth (but always dependent on and in sync with it).

Is this solution bad? If so why? What would be a better way to implement this?

Thanks!

Note: I didn’t include my code because I am massively simplifying the situation in this prompt– in reality Table element already exists, and is pretty complicated.

Note 2: I going to ask if I’d run into issues once I want to be able to modify elements in the tables, but I think I’m actually ok, since Table doesn’t manage its elements, just arrange and display them, and the buttons for adding and removing elements from a table are not contained within Table, so all that processing is happening at the level of the parent’s logic as passed down as part of props.rows

*Having something like <Table rows={sort(rowsFromParent)}/>every time I call Table is repetitive and error-prone, and since clicking on a table header determines sorting column, we’d actually have to have the parent element passing down an onClick() function in every case, which quickly and unnecessarily ramps up complexity).

Typescript: can you use constructor properties within a class’s private properties?

Is it bad practice to use a constructor properties of a class within a variable? I tried this and was surprised const name = new Name(time, course); worked, although I guess it makes sense since an instance of Eng needs those constructor properties to be made, then they’d be available to use elsewhere.

import { Name } from './Name'

class Eng {
   private _name = new Name(time, course);

   private constructor(time: String, course: String) {} 

   method1(){
      let results = name.convertTrials();

      return results;
   }
}