Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?

        <div class = "text">How much energy do you use?</div>
        <input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
        <button type="button" onclick="getInputValue();">Submit</button>
        <!-- Multiply InputValue by 3 and Add 2 —->

I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.

Retun value in nodejs

const https = require('https');
const xml2js = require('xml2js');
const parser = new xml2js.Parser({ attrkey: "ATTR" });

var tranid = 1647048190112;
var url = "https://alpha5.mobikwik.com/[email protected]&pwd=testalpha1@12345&txId=";

let req = https.get(url+tranid, function(res) {

    let data = '';
    res.on('data', function(stream) {data += stream;});
    res.on('end', function(){
        parser.parseString(data, function(error, result) {
             if(error === null) {
                  console.log(result);
             }else{
                  console.log(error);
        }
        return response
        });
    });
});

//This is my code and I want to return the value in nodejs

Firebase Analytics – Analytics.setUserId(id) is not auto-adding the user id to my events

I am using the Analytics’ DebugView to debug the tracked events of my app.

The Firebase documentation, says the following:

After setting a user ID, all future events will be automatically tagged with this value, and you can access it by querying for the user_id value in BigQuery. Adding a user ID will not affect any events previously recorded by Google Analytics.

When I read it, I supposed that doing

// Set the user id property for the `Analytics` service
analytics.setUserId(authUser?.uid ?? null);

would automatically include the user_id field in the properties of my events. But it is not happening…

Whats wrong with this? Is it the expected behavior? Should we include the property by ourselves when logging the events?

Check the search string uppercase and lowercase both

When the user will give input to the search box I want it to check if this string is available or not and display it. Currently, it is only showing results matched with uppercase to uppercase and lowercase to lowercase. But I want to match with the string uppercase and lowercase both at a time.
Example: Let’s say we are searching for TopLeader. when a user writes top it doesn’t show the result but when the user type Top the TopLeader result shows. I want when the user will search top or TOP still result will show.

Here is my code
Template:

<tbody>
  <tr v-for="item in filteredData" :key="item.id">
    <FLM :flm="item.flm" :flmCode="item.flm_code" />
  </tr>
</tbody>

Script:

data() {
return {
  worksheet: [],
  search: "",
};
},
computed: {
filteredData: function () {
  return this.worksheet.filter((result) => {
    console.log(result);
    return result.NSM.match(this.search);
  });
},
},
mounted() {
fetch("http://localhost:3000/worksheet")
  .then((response) => response.json())
  .then((data) => (this.worksheet = data))
  .catch((err) => console.log(err.msg));
  },

How to import .ts file inside the .js file?

I am developing VS code extension. For that I need to know how to import .ts file inside the .js file. I tried deafferent ways to import but it doesn’t work for me. Can someone help me?

Here’s the JS file code and Error says “Uncaught ReferenceError: require is not defined”

(function () {

const axios = require('axios'); // Error: Uncaught ReferenceError: require is not defined

const vscode = acquireVsCodeApi();

console.log("hello there from javascript");

document.getElementById("circlein").onclick = function(){
    var x = document.getElementsByClassName("outline")[0];
    if (x.style.display === "none") {
      x.style.display = "block";
    } 
    setTimeout(()=>{
      x.style.display = "none"
    },4000);
}

})();

Can someone know how to solve this?

How can I include the table title when I download it?

I am using https://github.com/gregnb/mui-datatables

How can I download the table title as well?

This is the table title, logo, data, and then the date:

enter image description here

codesandbox: https://codesandbox.io/s/download-the-title-as-well-q3ysil?file=/index.js

codes:

function App() {
  const columns = ["Name", "Title", "Location"];

  const options = {
    filter: true,
    filterType: "dropdown",
    responsive,
    tableBodyHeight,
    tableBodyMaxHeight
  };

  const data = [
    ["Gabby George", "Business Analyst", "Minneapolis"],
    [
      "Aiden Lloyd",
      "Business Consultant for an International Company and CEO of Tony's Burger Palace",
      "Dallas"
    ],
    ["Jaden Collins", "Attorney", "Santa Ana"],
    ["Franky Rees", "Business Analyst", "St. Petersburg"],
    ["Aaren Rose", null, "Toledo"],
    ["Johnny Jones", "Business Analyst", "St. Petersburg"],
    ["Jimmy Johns", "Business Analyst", "Baltimore"],
    ["Jack Jackson", "Business Analyst", "El Paso"],
    ["Joe Jones", "Computer Programmer", "El Paso"],
    ["Jacky Jackson", "Business Consultant", "Baltimore"],
    ["Jo Jo", "Software Developer", "Washington DC"],
    ["Donna Marie", "Business Manager", "Annapolis"]
  ];

  return (
    <React.Fragment>  
      <MUIDataTable
        title={
          <div>
            <img
              src="https://cdn.logo.com/hotlink-ok/logo-social.png"
              style={{ width: "50px" }}
            />
            Data {new Date().toDateString()}
          </div>
        }
        data={data}
        columns={columns}
        options={options}
      />
    </React.Fragment>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

how can I bundle multiple libraries with webpack and use them in a browser

Webpack describes a multi-main entry feature that seems to do exactly this, it bundles several libs into one file. The problem is that when I load that file only the last library on the list is available.

I’ve created a small demo on github.

There are 2 libraries each exporting a single symbol, only lib2.d2 is accessible from the test.html that loads the bundled JS. If you look in the bundle file you can see the code from lib1 but it’s not exported in any way that I can find.

The webpack config is below. I suspect the problem is that there’s no way to supply 2 library names when there’s out only output and so the last one over-writes the earlier ones.

const path = require('path');

module.exports = {
  entry: ['./js/lib1.js', './js/lib2.js'],
  module: {
    rules: [
      {
        test: /.js$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
    },
    filename: 'lib.js',
    path: path.resolve(__dirname, 'dist'),
  },
  "optimization": {
    "minimize": false,
    usedExports: true,
  },
  mode: "development",
};

If you’re curious why I would want to do this, I’m doing some development on wix.com. The only way to push JS files up to their server is copy/paste one at a time. Bundling a bunch of stuff into one file will save me some pain. My current work-around is to output to multiple files and then cat them all together with something export const exportLib1 = lib1 for each one. That gives me a JS file that I can import and access each one but there must be an easier way.

Unable to map nested array data in JavaScript?

Here, I have nested array object categories which have nested array objectproduct. product contains name, price, discount, unitsold properties with images array object which contains image url property.

How can I map each product name to it’s own image url?

Here is the whole object structure

{
  "data": {
    "categories": [
      {
        "categoryId": "aeb50ed6-580d-a065-383a-e3932fbec6a1",
        "name": "Electronics",
        "products": [
          {
            "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2",
            "name": "Small Soft Salad",
            "price": 841,
            "discount": 23,
            "unitsSold": 5,
            "images": [
              {
                "url": "https://shoplly-api.techawks.io/storage/511dBXGmAtL._AC_UL320_.jpg",
                "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2"
              },
              {
                "url": "https://shoplly-api.techawks.io/storage/71MIvKxxSvL._AC_UL320_.jpg",
                "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2"
              },
              {
                "url": "https://shoplly-api.techawks.io/storage/81loLb-NTYL._AC_UL320_.jpg",
                "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2"
              },
              {
                "url": "https://shoplly-api.techawks.io/storage/81goU9h-jnL._AC_UL320_.jpg",
                "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2"
              },
              {
                "url": "https://shoplly-api.techawks.io/storage/61pUul1oDlL._AC_UL320_.jpg",
                "productId": "f1ea5d7a-c26e-d850-52b5-9ac4c19668f2"
              }
            ]
          },
          {
            "productId": "b2d38cf6-b8c7-6449-e13a-8ef3bdd12dd0",
            "name": "Tasty Plastic Pants",
            "price": 250,
            "discount": 44,
            "unitsSold": 2,
            "images": [
              {
                "url": "https://shoplly-api.techawks.io/storage/511dBXGmAtL._AC_UL320_.jpg",
                "productId": "b2d38cf6-b8c7-6449-e13a-8ef3bdd12dd0"
              },

Here is my react component

import React from "react";
import { useQuery, gql } from "@apollo/client";
import useStore from "./store/store";

const FILMS_QUERYy = gql`
  {
    categories {
      categoryId
      name
      products {
        productId
        name
        price
        discount
        unitsSold
        images {
          productId
          url
        }
      }
      subCategories {
        name
        subCategoryId
        categoryId
      }
    }
  }
`;

const Hero = () => {
  const filter = useStore((state) => state.filter);
  const furniture = useStore((state) => state.furnitures);
  const electronic = useStore((state) => state.electronics);
  const accessorie = useStore((state) => state.accessories);
  const vehicle = useStore((state) => state.vehicles);
  const fashion = useStore((state) => state.fashions);
  const { data, loading, error } = useQuery(FILMS_QUERYy);
  console.log(JSON.stringify(data, null, 2));
  return (
    <div>
      <div className="flex space-x-10 justify-center items-center">
        <div onClick={furniture}>Furnitires</div>
        <div onClick={electronic}>Electroinics</div>
        <div onClick={accessorie}>Vehicles</div>
        <div onClick={vehicle}>Accessories</div>
        <div onClick={fashion}>Fashion</div>
      </div>
      <div className="flex space-x-16 p-4 mt-10">
        <div className=" w-64  bg-green-500">
          {data?.categories[filter]?.subCategories?.map((launch) => (
            <div key={launch.name}>{launch.name}</div>
          ))}
        </div>
        <div className="flex-1 p-10 font text-2xl  bg-green-500 ">
          {" "}
          <div className="grid grid-cols-2 gap-2">
            {data?.categories[filter]?.products?.map((product) => (
              <div className="" key={product.name}>
                <div className="  bg-white rounded">
                  
                  <div>{product?.name}</div>
                  <div>{product?.price}</div>
                  
 
          </div>
        </div>
      </div>
    </div>
  );
};

export default Hero;

In this case, I tried to map product name and price and I would like to map image url likewise.

How can I do that? Thanks
Thanks

Hamburger Menu disappears after one use

I have a website which has a navbar that turns into a hamburger menu at (max-width: 414px). The Hamburger menu works fine when I view it through the toggle device toolbar on both chrome and safari but when I open it on an actual iPhone, the menu disappears after one use.

enter image description here

Not really sure how to go about fixing this problem, any advice is appreciated

HTML

<nav>
        <div class="logo" style="font-family: VCRS;"><h2>MY COILY STORY</h2></div>
        <div class="openMenu"><i class="fa fa-bars fa-3x" ></i></div>
        <ul class="mainMenu"  style="font-family: VCRS;">
        <li><a href="#home" class="active" style="font-family: VCRS";>Projects</a></li>
                <li><a href="#home"  style="font-family: VCRS;">Home</a></li>
                <li><a href="#about" style="font-family: VCRS">About</a></li>
                <li><a href="#" style="font-family: VCRS">Gallery</a></li>
                <li><a href="./Contact/index.html" style="font-family: VCRS">  Contact</a><li>
                    <div class="x">
                <div class="closeMenu"><i class="fa fa-times fa-4x"></i></div>
            </div>
        </ul>           
    </nav>

CSS

@media only screen and (max-width: 414px)  {


    nav .mainMenu {
        height: 100vh;
        position: fixed;
        top: 0;
        right: 0;
        left: 0;
        z-index: 10000;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: black;
        transition: top 1s ease;
        display: none;
    
    }

    nav .mainMenu .closeMenu {
        display: block;
        position: absolute;
        top: 60px;
        right: 50px;
        transition: top 1s ease;
    }

    nav .openMenu {
        display: block;
          
    }

    i {
        display: inline-block;
        padding: 12px;
        
        margin-top: -40%;
        left: ;
    }


.closeMenu {
    position: absolute;
    margin-top: -538px;
    left: 131px;

}

 nav .logo {
    margin: 6px;
    font-size: 3.8vw;
    cursor: pointer;
      letter-spacing: 0.2rem;
      margin-left: 4%;
      margin-top: 0.5%;

}

nav a {
    font-size: 3vw;
}


nav .mainMenu li a {
    display: inline-block;
    padding: 15px;
    text-decoration: none;
    text-transform: uppercase;
    color: white;
    font-size:  5vw;
}

nav ul ul ul li {
    position: relative;
    margin-top: -60px;
    left: 150%;
    z-index: 10000;

   }
   nav ul ul li {
    width: 100%;
    float: none;
    display: list-item;
    position: relative;
    z-index: 10000;
    white-space: normal;
    margin-left: 90%;
    margin-top: -30%;
  
}

JS

const mainMenu = document.querySelector('.mainMenu');
const closeMenu = document.querySelector('.closeMenu');
const openMenu = document.querySelector('.openMenu');




openMenu.addEventListener('click',show);
closeMenu.addEventListener('click',close);

function show(){
    mainMenu.style.display = 'flex';
    mainMenu.style.top = '0';
}
function close(){
    mainMenu.style.top = '-100%';
}

Link to codepen: https://codepen.io/Ayanfe/pen/NWXwOEL

Redux Saga with socket.io stacked loops results in data duplication

I’m currently building a simple chat feature in my app using redux saga. Chat successfully entered from the emit server to the client

But the problem is, so when I move from the chat page and then back to the chat page, the last chat data sent will be duplicated to 2. Then when I move again and return to the chat page, the sent chat will be 3 and so on.

i think this happened maybe because the listener loop on fetchKonsultasi() function was stacked

Here is a dispatch function onGetKonsultasi() to listen to emits and onGetListKonsultasi() to retrieve chat list data from the server. Chat data is stored in the dataListKonsultasi, when there is an issue from the server, the dataListKonsultasi state will be updated

Someone help me, I really appreciate your help

index.js

useEffect(() => {
    onGetListKonsultasi()
    onGetKonsultasi()
}, [])

------

Konsultasi.propTypes = {
  dataKonsultasi: PropTypes.object,
  dataListKonsultasi: PropTypes.object,
  onGetKonsultasi: PropTypes.func,
  onGetListKonsultasi: PropTypes.func,
}

const mapStateToProps = ({ konsultasiReducer }) => ({
  dataKonsultasi: konsultasiReducer.dataKonsultasi,
  dataListKonsultasi: konsultasiReducer.dataListKonsultasi,
})

const mapDispatchToProps = dispatch => ({
  onGetKonsultasi: () => dispatch(getKonsultasi()),
  onGetListKonsultasi: () => dispatch(getListKonsultasi()),
})

export default connect(mapStateToProps, mapDispatchToProps)(Konsultasi)

saga.js

function createSocketConnection(url) {
  return io(url)
}

function createSocketChannel(socket) {
  return eventChannel(emit => {
    const eventHandler = event => {
      emit(event)
    }

    const errorHandler = errorEvent => {
      emit(new Error(errorEvent.reason))
    }

    socket.on("AdminReceiveMessage", eventHandler)

    socket.on("error", errorHandler)

    const unsubscribe = () => {
      socket.off("AdminReceiveMessage", eventHandler)
    }

    return unsubscribe
  })
}

function* fetchKonsultasi() {
  const socket = yield call(createSocketConnection, env.SOCKET_URL)
  const socketChannel = yield call(createSocketChannel, socket)

  while (true) {
    try {
      const response = yield take(socketChannel)
      yield put(updateListKonsultasiSuccess(response))
    } catch (err) {
      console.log("socket error: ", err)
    }
  }
}

function* fetchListKonsultasi() {
  try {
    const response = yield call(getListKonsultasi)
    yield put(getListKonsultasiSuccess(response))
  } catch (error) {
    yield put(getListKonsultasiFail(error))
  }
}

export function* watchSocket() {
  yield takeEvery(GET_KONSULTASI, fetchKonsultasi)
  yield takeEvery(GET_LIST_KONSULTASI, fetchListKonsultasi)
}

function* konsultasiSaga() {
  yield all([fork(watchSocket)])
}

reducer.js

case GET_LIST_KONSULTASI_SUCCESS:
  return {
    ...state,
    dataListKonsultasi: action.payload,
  }


case UPDATE_LIST_KONSULTASI_SUCCESS:
  return {
    ...state,
    dataListKonsultasi: {
      users: { ...state.dataListKonsultasi.users },
      data: [...state.dataListKonsultasi.data, action.payload],
    },

dataListKonsultasi Structure :

{
    "users": {
      ......
    },
    "data": [
        {
           ..chat_data...
        },
        {
           ..chat_data...
        },
    ]
}

How to stop any action if index of array is not available in count

I’m displaying objects from the array. example :

export default function App() {
  const data = [
    { id: 1, more: "string 1" },
    { id: 2, more: "string 2" },
    { id: 3, more: "string 3" }
  ];
  // here if index becomes 4 it breaks as there is no object in the data with index 4 
  const [index, setIndex] = React.useState(0); 
  const submitHandler = () => {
  // probably there we need any type of if statement but I don't; know how to compare with index
    setIndex(index + 1);
  };

  const showDat = (data, index) => {
    return <p>{data[index].more}</p>;
  };

  return (
    <div className="App">
      <Container>
        <Col md={8}>
          <Card style={{ minHeight: "40rem" }}>
            {showDat(data, index)}
            <Card.Footer>
              <Button
                variant="outline-danger"
                onClick={submitHandler}
                className="mx-1"
              >
                {" "}
                Skip
              </Button>
              <Button variant="primary" onClick={submitHandler}>
                {" "}
                Continue
              </Button>
            </Card.Footer>
          </Card>
        </Col>
      </Container>
    </div>
  );
}

The problem is if index is not available in the array then code breaks and I want to add error handling, like if index is not equal then make the continue button disable or something like that.

So how can I compare the count of index of the array to index state ?
Running Example in CodeSandBox

How to do filter search in react js / JS?

How to do filter search in react js / JS?
I have a component where I am displaying product details on card e.g (producctId, amounts,natureAndContentsOfContainer,packagingDetails,unitOfMeasure,primaryContainerType,DispensingMode, Ingredient,dosageForm,packSize, productCategoty, productType, strengthPerUnit, tradeName, pic1) and I also want to filter search on Ingredient and dosageForm paramenter only. When I fetch data from API I get this array:

[
  {
    supplier: {
      companyName: "Asad",
      id: "61f0f796cc53c565a15e31a3",
    },
    productId: "6213738798dbb2ecf4c23ddd",
    productDetails: {
      amounts: "%3 v/v",
      barcodePrinted: true,
      dosageForm: "tablet",
      gtinNumber: "09567214",
      api: {
        name: "AMITRIPTYLINE",
        countryOfOrigin: "pakistan",
        approvedBy: "us_fda",
      },
      coloringAgents: { values: Array(0) },
      listOfExcipients: [],
      natureAndContentsOfContainer: "containing 0.5ml solution",
      packSize: "10 tablets",
      packagingDetails: "pack of 3 strips each with 10 tablets",
      pic1: "",
      pic2: "",
      pilLanguage: "english",
      primaryContainerType: "blister",
      strengthPerUnit: "10 mg",
      tradeName: "WELLTRIP",
      unitOfMeasure: "1 k",
      _id: "6213738798dbb2ecf4c23de0",
    },
  },
  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "abc" },
    productId: "623079ef4c177018a57963f0",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient:
        " Riboflavin, Selenium, citrus bioflavonoids, copper, Vitamin A, Vitamin B6, Pantothenic acid, Vitamin E, Vitamin B12, Zinc, chromium, carotenoids, Folic acid, biotin, Iron, Magnesium, Manganese, Niacin, Thiamine, Vitamin d, grape seed , Flaxseed Oil, Vitamin C, iodine",
      coloringAgents: { values: Array(0) },
      dosageForm: "Tablet",
      listOfExcipients: [],
      packSize: "30 Tablet",
      preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "WELLKID IMMUNE CHEWABLE ",
      _id: "623079ef4c177018a57963f3",
    },
  },

  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "xyz" },
    productId: "623079ef4c177018a57963ee",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient: " lactobacillus acidophilus",
      coloringAgents: { values: Array(0) },
      dosageForm: "Capsule",
      listOfExcipients: [],
      packSize: "15 Capsule",
      preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "LACTOBIOTIX",
      _id: "623079ef4c177018a57963f6",
    },
  },
];

Note: I write only 3 product details. It can be 100+ as well.

Note: Searching parameters are Ingredient & dosageForm.

Now I want that if user search about Ingredient or dosageForm in search bar if data found then only show those arrays that contains searched input data and other data should be neglected.

How to web scrap an Interective web page with Rselenium

I want to web scrap all properties from this web page.

When I tried the following code, I only get the details of 1 property on the page.

library(tidyverse)
library(rvest)
library(RSelenium)
library(stringr)

rD <- rsDriver(browser = "chrome",port = 4234L,chromever = "99.0.4844.51")
remDr <- rD[["client"]]
# test Willhaben
goTo <- remDr$navigate("https://www.immobilienscout24.de/Suche/de/bayern/muenchen/haus-kaufen?pagenumber=3")

Lego <- read_html(remDr$getPageSource(goTo)[[1]])   

rooms <- Lego %>% html_element(".iLQwFF+ .iLQwFF .jXuiQ") %>%
  html_text()

address <- Lego %>% html_element("#skip-to-resultlist .hdZkVR") %>%
  html_text()

cost <- Lego %>% html_element(".result-list-entry__primary-criterion:nth-child(1) .font-highlight") %>%
  html_text()

surface <- Lego %>% html_element(".result-list-entry__primary-criterion:nth-child(2) .font-highlight") %>%
  html_text()

href <- Lego %>% html_element("a.result-list-entry__brand-title-container ") %>%
  html_attr('href')
apt_link <- paste0("https://www.immobilienscout24.de",href)


Munich_flat <- data.frame(apt_link, rooms, surface, cost, address)

The result looks like this.
enter image description here

How can I web scrap all properties on this page?
Thank you in advance.

Unable to get a ‘length’ property from an HTML element (array) using .hasAttribute / .hasOwnProperty methods

I have problem of getting a ‘length’ property of an array (in this case a table row), which clearly says that it has the property of length after applying the method getAttributeNames().

All the methods I try to apply (.hasOwnProperty, .hasAttribute. array.length) just return the boolean or undefined.

Might be a stupid question, but I am a newbie, and it kind of bothered me so much so I had to ask.
I hope I have explained my issue clearly.

I attach a page just in case.
https://rahulshettyacademy.com/angularAppdemo/library

enter image description here

d3 is not allowing for upload of csv file

I have this segment of code that is meant to upload a csv file for analysis on javascript using d3.

import * as d3 from 'd3'
// Materials
d3.csv("disney_plus_shows.csv", function(data) {
    console.log(data);
});

However, I am noticing that when I run npm build dev, the file cannot be found.

I am recieving this error
I have also tried placing copies of this csv file outside the src directory and root directory. I am not sure why I am unable to load it.