TypeError: val.replaceAll is not a function

Here is my code, I want to replace vowels in a string with the index values but when I was running the code I’m getting an error called “TypeError: val.replaceAll is not a function”.

I also used replace() method(got 2 l3v1 j0vasscript) in place of replaceAll() method but I didn’t get the desired output.

let val = "I love JavasScript";
val = val.toLowerCase();
let vowels = ['a', 'e', 'i', 'o', 'u'];

vowels.forEach((letter, index) => {
    val = val.replace(letter, index);
});
console.log(val);

i have to click on the button twice to post data to api in react

I have console.log(ed) the values while executing and what happens is on the first click, inputValue is sent with a null string to api, then on the next click the inputValue with string is sent to api. I have already changed the value of inputValue using the setter function in input tag with onChange function and then i have called the api so How do i fix it so it sends it on the first click.

const InputEmail = () => {

  const navigate = useNavigate()

  const [inputValue, setInputValue] = useState('')
  const [apiData, setApiData] = useState('')
  const [isError, setIsError] = useState(false)

  // useEffect(() => {
  //   //API()
  // }, [])

  const API = () => {
    console.log(inputValue)
    axios
      .post(url, {
        email: inputValue
      })
      .then((response) => {
        setApiData(response.data)
      })   
      console.log(apiData.is_active)
  }
  
  const handleSubmit = () => {
    API()
    if(apiData.is_active) {
      localStorage.setItem('email',inputValue)
      navigate("/assessment")
    } else {
      setIsError(true)
    }
  }

  return (
    <div className='main'>
        <FormControl>
          <h2 className='text'>Registered Email address</h2>
          <Input id='email' type='email' value={inputValue} onChange={e => setInputValue(e.target.value)}/>
          {
            isError ? <FormHelperText color='red'>Email not found. Please enter registered email</FormHelperText> : null
          }
          <Button
            mt={4}
            colorScheme='teal'
            type='submit'
            onClick={handleSubmit}
          >
            Submit
          </Button>
        </FormControl>
    </div>
  )
}

why is ‘mouseleave’ not triggered when triggering ‘mouseenter’ programmatically?

I’m writing a Next.JS app, and creating a useHover() hook to handle hover events via Javascript by using ‘mouseenter’ and ‘mouseleave’ events, and
I noticed that when I triggering ‘mouseenter’ programmatically:

let mouseenter = new Event('mouseenter');
refElement.current.dispatchEvent(mouseenter);

‘mouseleave’ event is not triggered anymore automatically (which I need for my logic).
Why tho? Am I missing something? BTW all listeners are set correctly, everythings (mouse events) work as intended when not triggering programmatically, but for some reason, manual triggering break automatic ‘mouseleave’.

How to implement sum(1)(2)(3) === 6 [duplicate]

I was asked to implement this function during an interview. It should chain its calls and, when the last call is made, it should return the sum of arguments used in all the previous calls.

sum(1) === 1;
sum(1)(2) === 3;
sum(1)(2)(3) === 6;

Is it even possible to implement such a function?

How to use useForm to validate input while using localStorage

I’m trying to validate a simple form with a single input just for practice. I also don’t want the value that the user types in the input to disappear after page refresh, for that reason, I did a little bit of searching and found out about saving that data using localStorage. After trying to implement that for a while, I managed to do that, when I refresh the page, the value is still there. However, now, when I’m trying to validate the form using useForm from react-hook-form, It just doesn’t work for some reason, when I try to use that same useForm logic with an input without using localStorage, It works just fine, but while trying to add localStorage functionality, then it doesn’t. I hope I’m describing my problem at least okey, here’s the code :


import React, {useEffect, useState } from "react";
import "./App.css"
import { useForm } from "react-hook-form";

const getForm = () => {
  const storedValues = localStorage.getItem("form");
  if(!storedValues) return {
      name: "",
      age: ""
    }
  return JSON.parse(storedValues);

}

function Home() {
 
 

  const [values, setValues] = useState(getForm)

  const {register, handleSubmit, watch} = useForm();

  const handleChange = (e) => {
    setValues((previousValues) => ({
      ...previousValues,
      [e.target.name]: e.target.value,
    }))
  }

  const onSubmit = async data => { console.log(data); };

  useEffect(()=>{
    localStorage.setItem("form", JSON.stringify(values))
  }, [values])
  
  return (
    
    <div className="container">
    <form onSubmit={handleSubmit(onSubmit)}>
      <input value={values.name} onChange={handleChange} name="name" placeholder="name"  />
      <input value={values.age} onChange={handleChange} name="age" placeholder="age"/>
      <button type="submit">Submit</button>
    </form>

    </div>
    )
}


export default Home;

This code works fine since I’m not adding useForm register to the input, but if I do that, then It gets buggy. I’m trying to find a solution on how to add that {…register} method without messing up the localStorage functionality, thank you in advance !

how to round digit if third decimal digit is greater than zero in javascript?

is it possible to round the digit using javascript.
Condition : we need to show number upto two decimal place. if third decimal digit is greater than zero i need to round off.

function roundNumberV1(num, scale) {
    if(!("" + num).includes("e")) {
        return +(Math.round(num + "e+" + scale)  + "e-" + scale);
    } else {
        var arr = ("" + num).split("e");
        var sig = ""
        if(+arr[1] + scale > 0) {
            sig = "+";
        }
        var i = +arr[0] + "e" + sig + (+arr[1] + scale);
        var j = Math.round(i);
        var k = +(j + "e-" + scale);
        return k;
    }
}


console.log(roundNumberV1(110.3724 ,2))

Expected output: 110.38
Current output : 110.37

if you see number 2 (third decimal)is greater than zero . I need to increase second decimal digit

TextField loses focus on each keystroke

I have an MUI textfield inside a Dialog. On each keystroke, the whole dialog is re-rendered and focus is lost on the textField. Each new character I add is persistent.

This is my dialog where the textfield and onChange are located.

const [action, setAction] = useState("");
function ActionDialog() {
    return (
        <Dialog open={open} onClose={handleClose} fullWidth maxWidth="sm">
            <DialogTitle>Action ID: {open}</DialogTitle>
            <DialogContent>
                <TextField
                    value={action?.Comment}
                    onChange={(e) => {
                        setAction((prev) => {
                            return { ...prev, Comment: e.target.value };
                        });
                    }}
                    label="Comment"
                    variant="outlined"
                    size="small"
                />
            </DialogContent>
        </Dialog>
    );
}

Script tag not loading in HTML

I’m new using script in HTML, and I’m following a tutorial, where he loads the script after the body (loading reasons).

In my code, I need to put the script in the head section and after the body. If I remove one of them stops working.

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>JQuery Selectors</title>
    <script src="../JS/JQ.js" type="text/javascript"></script>
    <script src="../../../JQuery/jq.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>Events in JQuery</h1>

    <img src="../../../Media/word-image-1.png" alt="image" id="img1" width="1000px">
    <button id="btn">Click</button>
  </body>
  <script src="../JS/JQ.js" type="text/javascript"></script>
  <script src="../../../JQuery/jq.js" type="text/javascript"></script>
</html> 

JS:

$("button").click(() => {
  $("#img1").css("width", "500px");
});

Video

Invert Map in Javascript [closed]

const teacherCourseMap = {
"Doris Wilson": ["Music", "Arts", "History"],
"Amy Smith": ["Sports", "Physics", "History"],
"Geraldine Carpenter": ["Music", "History", "Chemistry"],
"Ruth Carman": ["Chemistry", "Physics"],
"Abigail Marlow": ["English", "Arts"]
};

We have this object you need to write a function that invert the object value with keys, for example this function will return object with courses as keys and value will be array of teachers who are teaching the course.

output will be like this :

{
"Music":["Doris Wilson","Geraldine Carpenter"],
"Arts":["Doris Wilson","Abigail Marlow"],
"History":["Doris Wilson","Amy Smith","Geraldine Carpenter"],
"Sports":["Amy Smith"],
"Physics":["Amy Smith","Ruth Carman"],
"Chemistry":["Geraldine Carpenter","Ruth Carman"],
"English":["Abigail Marlow"]
};

Javascript disappears in WordPress

I’m using the Tawk.to plugin to add a live chat to my website, and want to let customers open the chat by clicking a text link. Tawk.to gave me this link but when I paste that into my WordPress editor it disappears as soon as I save the page. I paste it in the text screen as well as by inserting it as a hyperlink on the visual editor screen.

This is the link: <a href="javascript:void(Tawk_API.toggle())"> Click to Chat </a>

This is what I completely have on the website:

<div class="text">
<div class="phone"><strong>Vragen?</strong> <i class="fa fa-comments"></i><a href="javascript:void(Tawk_API.toggle())"> Click to Chat </a></div>

Does anyone know why it disappears and how it can be fixed?

h.265 can’t be played in browser

I am building a custom video player, but it seems like the <video /> tag can’t play H.265 files. I compressed files with ffmpeg, but I can’t play them in the web. Even when I redirect to the source the browser can’t play the file. Is there a way to play the files or build a custom player that is able to play it? I read that it is able to run h265 in some browsers. Is there a way to process the file on the device and play it then?

‘RequestDeviceOptions’: The provided value cannot be converted to a sequence

I am using a modified version of the sample code for Bluetooth device-information using the Web Bluetooth API.

The Bluetooth device was tested independently using NRF Connect app on my iPhone and everything works as intended. I used the UARTService ID as indicated on the NRF Connect app and used it to set OptionalServices. See the following code snippet.

let UARTService = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
    let UARTCharRX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
    let UARTCharTX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
    let options = {};
    
    //options.services = UARTService;
    
    if (document.querySelector('#allDevices').checked) {
        options.acceptAllDevices = true;
        options.optionalServices = UARTService;
    } else {
        options.filters = filters;
    }

    console.log('Requesting Bluetooth Device.........');
    console.log('with ' + JSON.stringify(options));
    navigator.bluetooth.requestDevice(options)
        .then(device => {
            console.log('> Name:             ' + device.name);
            console.log('> Id:               ' + device.id);
            console.log('> Connected:        ' + device.gatt.connected);
            return device;
        
        }).then(device => {
            return device.gatt.connect();
        
        }).then(function (server) {
            console.log("Connected ?  " + server.connected);
            return server.getPrimaryService(UARTService);
        
        }).then(function (result) {
            console.log("DEvice information ", result);
        
        }).catch(error => {
            console.log('Argh! ' + error);
        });

I get the following error:

Browser is WebBluetoothEnabled
device-info.js:37 Requesting Bluetooth Device.........
device-info.js:38 with {"acceptAllDevices":true,"optionalServices":"6e400001-b5a3-f393-e0a9-e50e24dcca9e"}
device-info.js:57 Argh! TypeError: Failed to execute 'requestDevice' on 'Bluetooth': Failed to read the 'optionalServices' property from 'RequestDeviceOptions': The provided value cannot be converted to a sequence.

Searching for 'RequestDeviceOptions': The provided value cannot be converted to a sequence. on stackoverflow and github issues was without answers.

I suspected a wrong Service UUID but on checking twice revealed it was correct.

Prevent negative values

in my shopping cart, i want to compare available stock and the quantity the user wants to buy, i dont know why it is not working properly. it works on some items and some it wont work. even when the item available is greater than item demanded, it keeps saying exceeded and when i input a greater value, it will work.

    $(document).on('click', '.add_to_cart', function(){
        var product_id = $(this).attr("id");
        var product_ids = $('#prods_id'+product_id+'').val();
        var product_name = $('#name'+product_id+'').val();
        var product_cat = $('#cat'+product_id+'').val();
        var product_type = $('#type'+product_id+'').val();
        var product_size = $('#size'+product_id+'').val();
        var product_price = $('#price'+product_id+'').val();
        var product_cost_price = $('#cost_price'+product_id+'').val();
        var product_quantity = $('#quantity'+product_id).val();
        var product_unit_quantity = $('#unit_qty'+product_id).val();
        var product_unit_carton = $('#unit_carton'+product_id).val();
        var product_stock_qty = $('#stock_qty'+product_id).val();
        var action = "add";

        if(product_quantity > product_stock_qty){
            alert("Exceeded Available Quantity");
        }

    else if (product_quantity > 0){
            $.ajax({
                url:"action.php",
                method:"POST",
                data:{product_id:product_id, product_ids:product_ids, product_cat:product_cat, product_name:product_name, product_type:product_type, product_size:product_size, product_price:product_price, product_cost_price:product_cost_price, product_quantity:product_quantity, product_unit_quantity:product_unit_quantity, product_unit_carton:product_unit_carton, action:action},
                success:function(data)
                {
                    load_cart_data();
                    alert("Item has been Added into Cart");
                }
            });
        }
        else
        {
            alert("Please Enter Number of Quantity");
        }
    });

thanks

Uncaught TypeError: Cannot read properties of undefined (reading ‘cityName’) at renderCitySelectors (script.js:30:41)

I cannot get this problem fixed. We fixed this error three times and it came back but I and my group are not sure how to fix it. Can someone please give me some light? We are trying to two use 2 APIS (Weather and Spotify) to give us data where depending on the temperature it will give you different playlists on spotify. So if it is a sunny or hot day you will be displayed data from the Spotify showing playlists that are used for sunny days.

var citySearchEl = $('#city-search-form');
var cityNameEl = $('#city-name');
var formalCityName;

// Variable(s)) used to get playlist
var weatherMain;
var weatherDescription;
var currentTemp;

// Get the city info from local storage to display
var cityObjArray = JSON.parse(localStorage.getItem("cityInfo")) || [];

var cityButtonEl = document.querySelector("#city-buttons");

//*******************************************************/
//             Meme/Inspiration code goes here                */
var memeFunction = function () {
  console.log("Meme Function call works");
};

//*******************************************************/
//             Weather section code goes here                */
var renderCitySelectors = function() {
  var length = cityObjArray.length;
  console.log("***************************************cityObjArray=" , cityObjArray);
  //cityObjArray.forEach(function(placeHolder, arrayIndex) {
    for (let arrayIndex=(length-3); arrayIndex<length; arrayIndex++){
    // Create button for city choices
    appendCity(cityObjArray[arrayIndex].cityName);
  }
}

var appendCity = function(cityName){

  // Create new city button and add it to the list
  var cityButton = $("<button class=button></button>").text(cityName).addClass("has-background-success-light is-responsive is-fullwidth mb-1");
  $("#city-buttons").prepend(cityButton);   // Append new city button element
}

var citySearchHandler = function (event) {
  event.preventDefault();

  // get cityName from input element
  var cityName = $("input:text").val();

  // if we have a city name, get lat/long, else error
  if (cityName) {
    getCityLatLong(cityName);
    // clear input field content
    cityNameEl.val("");
  } else {
    alert("Please enter a city name");
    return;
  }
};

var getCityLatLong = function (cityName) {
  // format the openwathermap api url
  var apiUrl =
    "https://api.openweathermap.org/geo/1.0/direct?q=" +
    cityName +
    "&appid=d89a7998c295640400d389063c3b71e9";

  // make a get request to url
  fetch(apiUrl)
    .then(function (response) {
      // request was successful
      if (response.ok) {
        response.json().then(function (cityData) {
          console.log("*******************************  data= ", cityData);
          if (!cityData[0]) {
            // no data returned for cityName
            console.log("no data returned - invalid city????");
          } else {
            // Prepare object to push into array and make new selector button
            formalCityName = cityData[0].name;
            const cityObj = {
              cityName: formalCityName,
              stateName: cityData[0].state,
              latitude: cityData[0].lat,
              longitude: cityData[0].lon,
            };
            cityObjArray.push(cityObj);
            localStorage.setItem("cityInfo", JSON.stringify(cityObjArray));

            // Add city button to search button list and get the weather
            appendCity(cityObj.cityName);
            getWeather(cityObj.latitude, cityObj.longitude);
          }
        });
      } else {
        alert("Error: Total Bummer");
      }
    })
    .catch(function (error) {
      alert("Unable to connect to OpenWeatherAPI");
    });
};

var getWeather = function (latitude, longitude) {
  // format the openwathermap api url

  var apiUrl =
    "https://api.openweathermap.org/data/2.5/onecall?lat=" +
    latitude +
    "&lon=" +
    longitude +
    "&exclude=minutely,hourly&units=imperial&appid=d89a7998c295640400d389063c3b71e9";

  // make a get request to url
  fetch(apiUrl)
    .then(function (response) {
      // request was successful
      if (response.ok) {
        response.json().then(function (data) {
          console.log("*******************************  data= ", data);
          if (!data.daily[0]) {
            // no data returned
            console.log("no data returned - invalid lat/lon????");
          } else {
            console.log("Loading weather data");

            // Load window for today's data
            const initialDate = new Date();

            $("#city-date").html(
              formalCityName + " (" + initialDate.toDateString() + ")"
            );

            // Get the icon and weather description
            var iconCode = data.current.weather[0].icon + "@2x";
            weatherMain = data.current.weather[0].main;
            weatherDescription = data.current.weather[0].description;
            var iconUrl =
              "https://openweathermap.org/img/wn/" + iconCode + ".png";
            $("#today-icon").html(
              "<img class=icon-size src='" + iconUrl + "'>"
            );

            // Display the temp/wind/humidity
            $("#today-temperature").text("Temp: " + data.current.temp + "F");
            $("#today-winds").text(
              "Winds: " + data.current.wind_speed + " MPH"
            );
            $("#today-humidity").text(
              "Humidity: " + data.current.humidity + " %"
            );

            // Display the UV index number
            $("#today-uv-index").text("" + data.current.uvi);

            // clear any old color class
            $("#today-uv-index").removeClass();

            // get the correct background color
            if (data.current.uvi <= 2) {
              $("#today-uv-index").addClass("has-background-success");
            } else if (data.current.uvi <= 5) {
              $("#today-uv-index").addClass("has-background-warning");
            } else if (data.current.uvi <= 7) {
              $("#today-uv-index").addClass("has-background-warning-dark");
            } else {
              $("#today-uv-index").addClass("has-background-danger-dark");
            }
            //****************************************************************************** */
            // Get weather description for playlist (for development only - remove!!!!!!!!!!!!)
            $("#weather-main").empty(weatherMainButton);
            $("#weather-description").empty(weatherDescriptionButton);
            var weatherMainButton = $("<button class=button></button>").text(
              weatherMain
            );
            $("#weather-main").append(weatherMainButton); // Append new city button element
            var weatherDescriptionButton = $(
              "<button class=button></button>"
            ).text(weatherDescription);
            $("#weather-description").append(weatherDescriptionButton); // Append new city button element
            //****************************************************************************** */
            currentTemp = data.current.temp;
            getPlaylist();
          }
        });
      } else {
        alert("Error: Total Bummer");
      }
    })
    .catch(function (error) {
      alert("Unable to connect to OpenWeatherAPI");
    });
};

var buttonClickHandler = function (event) {
  event.preventDefault();
  formalCityName = event.target.innerHTML;

  cityObjArray.forEach(function (placeHolder, arrayIndex) {
    // find the city to get the lat/long
    if (cityObjArray[arrayIndex].cityName === formalCityName) {
      getWeather(
        cityObjArray[arrayIndex].latitude,
        cityObjArray[arrayIndex].longitude
      );
    }
  });
};

//*******************************************************/
//             Spotify's code goes here                */

var getPlaylist = function () {
  var playlistOption;
  var globalTemp = currentTemp;
  console.log("currentTemp", currentTemp);
  if (globalTemp > 80) {
    playlistOption = "sunny";
  } else if (globalTemp < 80 && globalTemp > 40) {
    playlistOption = "Rainy";
  } else {
    playlistOption = "cold";
  }
  fetch(
    "https://v1.nocodeapi.com/babaphillips/spotify/FirIUjwQAgxPjCJN/search?q=" +
    playlistOption +
    "&type=playlist&perPage=3"
    )
    .then((response) => response.json())
    .then((result) => console.log(result))
    .catch((error) => console.log("error", error));
};

memeFunction();
renderCitySelectors();
citySearchEl.on('submit', citySearchHandler);
//$("#city-submit").on('submit', citySearchHandler);
cityButtonEl.addEventListener("click", buttonClickHandler)```