Using jQuery UI to open and close search box?

I’m setting up an autocomplete search box.

Here’s my current code:

$(document).ready(function(){
 
 $('#txtSearch').autocomplete({
     source: "https://example.com/search.php",
     minLength: 1,
     select: function(event, ui) {
         var url = ui.item.id;
         if (url != '#') {
             location.href = 'https://' + location.hostname + '/' + url
         }
     },
     open: function(event, ui) {
         $(".ui-autocomplete").css("z-index", 1000)
         $('.exo-search').css('border-bottom-left-radius','0');
         $('.exo-search').css('border-bottom-right-radius','0');
     }
 })
 
});

You can see here that someone starts typing and the results are loading, it sets the bottom border radius to 0.

 open: function(event, ui) {
     $(".ui-autocomplete").css("z-index", 1000)
     $('.exo-search').css('border-bottom-left-radius','0');
     $('.exo-search').css('border-bottom-right-radius','0');
 }

But if someone clicks away from the search box, the dropdown of results disappears like it’s supposed to, but the bottom border radius is still set to 0 instead of resetting back to 5px like it normally is.

Is there something wrong with my code or is that the normal behavior and I need to add something else?

How to put in checkboxes values into a session variable without any button clicks?

lets say i have a code pretty similar like this

<form>
  <input type="checkbox" name="account1" value="1">
  <input type="checkbox" name="account2" value="2">
  <input type="checkbox" name="account3" value="3">
  <input type="checkbox" name="account4" value="4">


  <button type="submit">Delete</button>
</form>

Now i want to store the value of the checkbox in a php session once the user checked the boxes without clicking the submit/delete button. I plan to use jquery/ajax for this but i still cant quite wrap my head around it since im very new to ajax or jquery.

To add more detail, the process is like this..
the user can select any account he wants he checked. lets say he checked an account on page 1. he then went to another page(pagination) and then went back to page 1, the checked boxes would still be checked.

how to read aws cpu usage using node?

i want to build a small app that reads the AWS CPU USAGE every 5 minutes lets say, i built the params, call the getMetricsStatistics but it keeps returning me an empty array, you know why? this is the code:

const aws = require('aws-sdk')
const dotenv = require('dotenv').config()

aws.config.setPromisesDependency()
aws.config.update({
  accessKeyId: process.env.EC2_ACCESS_KEY,
  secretAccessKey: process.env.EC2_SECRET_KEY,
  region: 'us-east-1',
})
const s3 = new aws.CloudWatch()

var params = {
  EndTime: new Date() /* required */,
  /* required */
  MetricName: 'EngineCPUUtilization',
  Namespace: 'AWS/S3',
  StartTime: new Date('Mon Dec 6 2021') /* required */,
  /* required */
  Dimensions: [
    {
      Name: 'Per-Instance Metrics' /* required */,
      Value: 'i-abbc12a7' /* required */,
    },
    {
      Name: 'StorageType',
      Value: 'AllStorageTypes',
    },
    /* more items */
  ],

  Period: 300 /* required */,
  Statistics: ['Average'] /* required */,
}
async function asyncMethod() {
  return await s3.getMetricStatistics(params, function (err, data) {
    if (err) console.log(err, err.stack)
    // an error occurred
    else {
      console.log(data)
    }
  }) // successful response
}

const d = asyncMethod()

response is always empty array in the data.Datapoints.

understanding this when adding new object’s properties/methods (Javascript) [duplicate]

I’m a newbie trying to understand the value of this, when adding a new property and a new method.
Adding new property:

const Person = function (fname, lname) {
    this.fname = fname;
    this.lname = lname;
};
const bob = new Person('Bob', 'Sinclair');
bob.fullName = `${this.fname} ${this.lname}`  

in this example,
this will refer to the global object, therefore the value of fullName will be undefined. I get it.

Adding new method:

bob.printFirstName = function () {
    console.log(this.fname);
}  

now, why is this equal to the object? why, since is a function, is not equal to the global object or undefined (depending we are in non-strict/strict mode), Because is it a method? therefore the this in a method is equal to the object? I don’t get it.

How to bind function in vue js v-model?

I asked a question which might be unclear to someone. So, I deleted that question and ask again with new approach. I have an API response something like this:

{
      id: 2,
      name: 'Item 1',
      items: [
        {
          slug: 'Phase 1',
          values: [
            {
              highValue: '12',
              lowValue: '8',
              color: 'red'
            },
            {
              highValue: '15',
              lowValue: '5',
              color: 'green'
            }
          ]
        },
        {
          slug: 'Phase 2',
          values: [
            {
              highValue: '14',
              lowValue: '6',
              color: 'red'
            },
            {
              highValue: '15',
              lowValue: '5',
              color: 'green'
            }
          ]
        }
      ]
    },
    {
      id: 3,
      name: 'Item 2',
      items: [
        {
          slug: 'CBC',
          values: [
            {
              highValue: '10',
              lowValue: '7',
              color: 'green'
            },
            {
              highValue: '12',
              lowValue: '3',
              color: 'red'
            }
          ]
        }
      ]
    }

I have static block for High Value, Low Value, Red & Green in my HTML. So, for those static blocks, I need to pick appropriate value from the response. For example, for High Value & Red block, I need to pick highValue from the response when color: 'red'. So, I write four function for example:

redHigh (item) {
      const res = item.filter(obj => {
        return obj.color === 'red'
      })
      return res[0].highValue
    }

Now, I tried to bind the function in v-model like this way:

               <v-text-field
                  outlined
                  :v-model="redHigh(sub.values)"
                  placeholder="High"
                ></v-text-field>

But, that was not working. If I wrote :value instead of :v-model, that would work. But, in that case I don’t get the changed value after clicking save button.

save (formIndex) {
      console.log(this.items[formIndex])
    }

enter image description here

How to solve that?

Codepen Demo

React.useMemo is re-rendering all items in array

I have a react component that stores a set of fruits in useState. I have a memoized function (visibleFruits) that filters fruits. I map visibleFruits to the dom.

The problem is, when i check a fruit, all visible fruits re-render.

I am expecting that only the selected one re-renders since it is the only one that is changing.

Is there a way for me to use this pattern but prevent all from re-rendering on check?

import React from 'react'

const Example = () => {
    const [fruits, setFruits] = React.useState([
        { id: 1, name: 'apple', visible: true, selected: false },
        { id: 2, name: 'banana', visible: false, selected: false },
        { id: 3, name: 'orange', visible: true, selected: false }
    ])

    const visibleFruits = React.useMemo(() => {
        return fruits.filter((f) => f.visible)
    }, [fruits])

    const handleCheck = (bool, id) => {
        setFruits((prev) => {
            return prev.map((f) => {
                if (f.id === id) {
                    f.selected = bool
                }
                return f
            })
        })
    }

    return (
        <div>
            {visibleFruits.map((fruit) => {
                console.log('** THIS RENDERS TWICE EVERY TIME USER SELECTS A FRUIT **')
                return (
                    <div key={fruit.id}>
                        <input
                            checked={fruit.selected}
                            onChange={(e) => handleCheck(e.target.checked, fruit.id)}
                            type='checkbox'
                        />
                        <label>{fruit.name}</label>
                    </div>
                )
            })}
        </div>
    )
}

export default Example

trying to implement Material Design Navbar in React

I’m scratching my head here trying to figure out why I can’t see the styling applied to my Navbar. I’ve installed all of the necessary modules but it’s not happening. My code is below. I was working on a custom Navbar but the material one is very slick so I wanted to try it instead.

Navbar code

import React, { useState } from 'react';
import {
  MDBContainer,
  MDBNavbar,
  MDBNavbarBrand,
  MDBNavbarToggler,
  MDBIcon,
  MDBNavbarNav,
  MDBNavbarItem,
  MDBNavbarLink,
  MDBBtn,
  MDBDropdown,
  MDBDropdownToggle,
  MDBDropdownMenu,
  MDBDropdownItem,
  MDBDropdownLink,
  MDBCollapse
} from 'mdb-react-ui-kit';

export default function NavbarMaterial() {
  const [showBasic, setShowBasic] = useState(false);

  return (
    <MDBNavbar expand='lg' light bgColor='light'>
      <MDBContainer fluid>
        <MDBNavbarBrand href='#'>Brand</MDBNavbarBrand>

        <MDBNavbarToggler
          aria-controls='navbarSupportedContent'
          aria-expanded='false'
          aria-label='Toggle navigation'
          onClick={() => setShowBasic(!showBasic)}
        >
          <MDBIcon icon='bars' fas />
        </MDBNavbarToggler>

        <MDBCollapse navbar show={showBasic}>
          <MDBNavbarNav className='mr-auto mb-2 mb-lg-0'>
            <MDBNavbarItem>
              <MDBNavbarLink active aria-current='page' href='#'>
                Home
              </MDBNavbarLink>
            </MDBNavbarItem>
            <MDBNavbarItem>
              <MDBNavbarLink href='#'>Link</MDBNavbarLink>
            </MDBNavbarItem>

            <MDBNavbarItem>
              <MDBDropdown>
                <MDBDropdownToggle tag='a' className='nav-link'>
                  Dropdown
                </MDBDropdownToggle>
                <MDBDropdownMenu>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Action</MDBDropdownLink>
                  </MDBDropdownItem>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Another action</MDBDropdownLink>
                  </MDBDropdownItem>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Something else here</MDBDropdownLink>
                  </MDBDropdownItem>
                </MDBDropdownMenu>
              </MDBDropdown>
            </MDBNavbarItem>

            <MDBNavbarItem>
              <MDBNavbarLink disabled href='#' tabIndex={-1} aria-disabled='true'>
                Disabled
              </MDBNavbarLink>
            </MDBNavbarItem>
          </MDBNavbarNav>

          <form className='d-flex input-group w-auto'>
            <input type='search' className='form-control' placeholder='Type query' aria-label='Search' />
            <MDBBtn color='primary'>Search</MDBBtn>
          </form>
        </MDBCollapse>
      </MDBContainer>
    </MDBNavbar>
  );
}

Here’s the code from my App.js with said Navbar

import React from "react";
import { Routes, Route } from 'react-router-dom';
import Header from './components/Header'
import NavbarBasic from './components/NavbarBasic';
import NavbarMaterial from './components/NavbarMaterial';
import About from './components/pages/About';
import Pests from './components/pages/Pests';
import { Ants, Bees, Roaches, Mice, Wasps, Bedbugs, Flies } from './components/Pests';
import Home from './components/pages/Home';
import Services from './components/pages/Services';
import Contact from './components/pages/Contact';

function App() {
  return (
    <div className="main">
      <Header />
      <NavbarMaterial />
      {/* These are the main routes and subpages */}
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/about' element={<About />} />
        <Route path='/pests-we-treat' element={<Pests />} />
        <Route path='/services' element={<Services />} />
        <Route path='/contact' element={<Contact />} />
        <Route path='/ants' element={<Ants />} />
        <Route path='/wasps' element={<Wasps />} />
        <Route path='/roaches' element={<Roaches />} />
        <Route path='/bedbugs' element={<Bedbugs />} />
        <Route path='/bees' element={<Bees />} />
        <Route path='/mice' element={<Mice />} />
        <Route path='/flies' element={<Flies />} />
      </Routes>
    </div>
  );
}

export default App;

Here’s my package JSON file with the dependencies.

{
  "name": "weinerpest",
  "homepage": "http://weinerpestservices.com",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.5.0",
    "@emotion/styled": "^11.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.36",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@fortawesome/react-fontawesome": "^0.1.16",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@mui/material": "^5.0.4",
    "@mui/styles": "^5.2.3",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.1.3",
    "history": "^5.1.0",
    "mdb-react-ui-kit": "^2.1.0",
    "mdbreact": "^5.2.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.3",
    "react-dom": "^17.0.2",
    "react-dropdown": "^1.9.2",
    "react-dropdown-router": "^1.0.1",
    "react-responsive": "^9.0.0-beta.4",
    "react-router-dom": "^6.0.2",
    "react-scripts": "4.0.3",
    "react-select": "^5.2.1",
    "styled-components": "^5.3.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Javascript, how to alternate class between elements. And go back to original when none of elements is selected

I’d like to request your help. Here’s what I’m trying to do.

I have a grid of six items. I wanna make the first item actived by default and whenether the user moves the mouse over one of the five remaing grid items, the class will be remove from the first item and applied the the current selected item. Once there’s no object with the cursor over it. The class will automatically be applied to the first element again.

const cards = document.querySelectorAll('.card');

function cardSelect() {
  cards.forEach(card => {
    card.addEventListener('mouseenter', () => {
      card.classList.add('active');
    });
    card.addEventListener('mouseleave', () => {
      card.classList.remove('active');
    });

    //If there's no actived element, then apply active class to the first item
    if (!card.classList.contains('active')) {
      cards[0].classList.add('active');
      //If there's any actived element, then remove the active class from the first item
    } else {
      cards[0].classList.remove('active');
    }
  })
}
cardSelect();
.grid {
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 200px);
  grid-template-areas: "item1 item2 item3" "item4 item5 item6";
}


/* line 1152, ../../PCX/sass/scss/style.scss */

.grid .card {
  color: #fff;
  font-size: 2rem;
  background-color: #0077ff;
  display: flex;
  align-items: center;
  justify-content: center;
}


/* line 1160, ../../PCX/sass/scss/style.scss */

.grid .card.active {
  background-color: #0000ee;
}


/* line 1164, ../../PCX/sass/scss/style.scss */

.grid .item1 {
  grid-area: item1;
}


/* line 1167, ../../PCX/sass/scss/style.scss */

.grid .item2 {
  grid-area: item2;
}


/* line 1170, ../../PCX/sass/scss/style.scss */

.grid .item3 {
  grid-area: item3;
}


/* line 1173, ../../PCX/sass/scss/style.scss */

.grid .item4 {
  grid-area: item4;
}


/* line 1176, ../../PCX/sass/scss/style.scss */

.grid .item5 {
  grid-area: item5;
}


/* line 1179, ../../PCX/sass/scss/style.scss */

.grid .item6 {
  grid-area: item6;
}
<div class="grid">
  <div class="item1 card">ITEM 1</div>
  <div class="item2 card">ITEM 2</div>
  <div class="item3 card">ITEM 3</div>
  <div class="item4 card">ITEM 4</div>
  <div class="item5 card">ITEM 5</div>
  <div class="item6 card">ITEM 6</div>
</div>

Could you guys give me a hand? It’s a logic issue and lack of js knowledge.

React Draggable property only being applied to final element in array

I am looking to add draggable list items to my DOM via JSX in react.

The expected output into the DOM should look like this:

<li draggable="true" style="border: 1px solid red;">Test Scenario 1</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 2</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 3</li>

But the actual output is:

<li style="border: 1px solid red;">Test Scenario 1</li>
<li style="border: 1px solid red;">Test Scenario 1</li>
<li draggable="true" style="border: 1px solid red;">Test Scenario 1</li>

Current code I have tried:

import React from 'react';
import { useDrag } from "react-dnd";

function LibraryItems(props) {

    const [{ isDragging }, dragRef] = useDrag(() => ({
        type: "li",
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
        }),
    }));

    
    // Declare and populate array of Library Scenarios
    const itemList = []
        
    props.items.map(item => {
        itemList.push(<li style={{border: 'red 1px solid'}} ref={dragRef}>{item.title}</li>);
    })

        
    return (
        <ul>
            {itemList}
        </ul>
    )
}

export default LibraryItems

Get worldposition of an object in React Three Fiber without onClick

currently I am creating a robot model in react. This robot model is in .glb format and I am using React Three fiber to paste every mesh object in to the scene (I got the names of the meshes from blender). Via zustand and my control function I can rotate some joints to move the robot in the direction of desire. My next goal is to “extract” each worldcoordinate of the joints and show them in my overlay close to the control buttons.
I already tried something like that:

<mesh
                    ref={joint_1}
                     onClick={(vectorEvent) => {
                       let vector = new THREE.Vector3();
                       vectorEvent.object.getWorldPosition(vector);
                       console.log(vector);
                     }}
></mesh>

but this only works when I click the joint I want the coordinate from. I want to do this with an onClick event on my control function(complete different function and not part of THREE nor GLTF) when I change some angles. Any Ideas?

Object destructuring in Javascript – trying to make sense

probably a bit of a silly question but I’m only a beginner and there’s something I am trying to understand properly.

When we have code like this:

const { userName } = await getUserProfile({ userId });

What exactly is happening here? Are we destructuring userName out of the getUserProfile object to be able to access that property? And does userId mean that the getUserProfile function has a parameter that is an object that has a property userId?

Sorry, if this is too beginner of a question but would really appreciate it if anyone had the time to explain this to me please.

Is it possible for Block level element inside of an In-line element?

I read that in HTML, a block-level element can’t be used inside of an In-line element. For example, <span>Hi <div>!</div></span> is not possible as <span> is an In-line element and <div> is a Block-level element.
But, I also read that <a></a> is an In-line element and have frequently seen <div> tags being used inside of a <a> tag. How is this possible and what am I missing?