Formating v-model make a decision if you meet the condition

I have one component that have one input, the input value indicates the unit of measurement, the measurements can be kilogram, gram, units, etc …

I have registered in the database

Kg = 0.1
g = 100
unit = 1

The type of input value, is selected from a select

so in my code I have:

<template>
    <tr>    
        <td class="product-quantity">
            <input
                class="quantity no-round-input"
                type="numeric"
                v-model="item.quantity"
                min="0"
                @keypress="isNumber($event)"
            />
        </td>
        <td class="product-price">
            <select
                name="unit"
                class="form-control"
                v-model="item.attributes.unit"
            >
                <option v-bind:key="unit.id" v-for="unit in units" :value="unit.abr">
                    {{ unit.unit }}
                </option>
            </select>
        </td>
    </tr>
</template>

the value I get from props, so in my vue I have:

<script>
export default {
      props: ["item"],
      watch: {
          'item.quantity' (){ 
            if( (this.item.quantity - Math.floor(this.item.quantity)) !== 0 ){
                this.item.quantity = this.item.quantity.toFixed(1);
            }else{
                this.item.quantity = this.item.quantity;
            }
    
          }
       },
       methods: {
        isNumber(evt) {
          evt = (evt) ? evt : window.event;
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
            evt.preventDefault();;
          } else {
            return true;
          }
        },
     }
   }
</script>

so, I just want that when v-model is Kg, the value input is in decimals, only decimals to Kg, so I implemented in propiety watch to observe input(item.quantity) but it’s not working, do you can help me please?

creating new force graph with react+ts and d3

im trying to create a simple force graph with react+ts and d3.

after long research everything i found online isn’t updated lately.
so i would like to use your help with that.

Main issue
i have now is to connect my nodes with a line

heres my code:

import React from "react";
import { forceSimulation, forceManyBody, forceLink, forceCenter } from 'd3-force'
import d3 ,{ SimulationNodeDatum } from "d3";
import { Box } from "@mui/system";


type Node = {
  id: string;
  class: string;
  x?: string;
  y?: string;
}

type Link = {
  source: string;
  target: string;
  connectionType: string;
}

the data (in the same file)

const { links, nodes } = {
  nodes: [{
    id: "honda",
    class: "cars",
  }, {
    id: "civic",
    class: "cars",
  },{
    id: "toyota",
    class: "cars",
  },{
    id: "corola",
    class: "cars",
  }],
  links: [{
    source: 'civic',
    target: 'honda',
    connectionType: 'm2o'
  },{
    source: 'corola',
    target: 'toyota',
    connectionType: 'm2o'
  }]
}

and heres the component

function Rd4Component (): JSX.Element {
  const simulation = forceSimulation(nodes as SimulationNodeDatum[]);
    simulation
      .force('charge', forceManyBody().strength(-100))
    .force('link',
      forceLink(links)
        .id((d) => (d as Node).id)
        .distance(75)
    )
      .force("center", forceCenter(300, 300));

  const svg = d3.select('#Target');

  const node = svg
      .selectAll("circle")
      .data(nodes)
      .enter()
      .append("circle")
      .attr("r", 15)
      .attr("stroke", "green")
      .attr("stroke-width", 0.5)
      .style("fill", "red");

  const link = svg
      .selectAll('path.link')
      .data(links)
      .enter()
      .append("path")
      .attr("stroke", "black")
      .style("fill", "none");


  function ticked() {
     link
       .attr("x1", function (d: any) {
         return d.source.x;
       })
       .attr("y1", function (d: any) {
         return d.source.y;
       })
       .attr("x2", function (d: any) {
         return d.target.x;
       })
       .attr("y2", function (d: any) {
         return d.target.y;
       });

    node
      .attr("cx", function (d: any) {
        return d.x;
      })
      .attr("cy", function (d: any) {
        return d.y;
      });

    // label
    //   .attr("x", function (d: any) {
    //     return d.x + 5;
    //   })
    //   .attr("y", function (d: any) {
    //     return d.y + 5;
    //   });
  }

  simulation.nodes(nodes as SimulationNodeDatum[])
    .on("tick", ticked)


  return <Box sx={{overflowY: "scroll"}}>
    <svg height={600} width={600} id="Target" />
  </Box>
}

export default Rd4Component;

and here the results
the render
inspected results

i cant find a way to render the lines, looked at the docs and even paid online courses. seems that nothing works.. )):

thanks in advanced

Uploading .txt files to the chat discord js

I have a txt file full of stuff that I want the bot to upload to the chat. So far I have found no such code on the internet and I have tried nothing yet. Can anyone write me a script that uploads the whole txt file to the chat(not the content, UPLOAD the text file)? Thanks.

LIFI VLC with JS

I am making a code to send information by bits, it is LIFI information that the flash uses to send said information. I have managed to turn on the torch from the web with JS but at the time of sending the message I have an error, any idea what I can do?

The code is this:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
  <div class="input-group mt-3 ml-auto mr-auto">
    <input id="msg" class="form-control" type="text" name="msg" placeholder="Type message here..." />
    <div class="input-group-append">
        <button id="toggle" class="btn btn-primary">Send</button>
    </div>
<script>
//have a console on mobile
var consoleOutput = document.getElementById("console");
const log = function(msg){
    //  consoleOutput.innerText = `${consoleOutput.innerText}n${JSON.stringify(msg)}`;
    document.getElementById("console").innerText = msg;
    console.log(msg);
}

//Test browser support
const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;

if (SUPPORTS_MEDIA_DEVICES) {
  //Get the environment camera (usually the second one)
  navigator.mediaDevices.enumerateDevices().then(devices => {
  
    const cameras = devices.filter((device) => device.kind === 'videoinput');

    if (cameras.length === 0) {
      log('No camera found on this device.');
    }
    const camera = cameras[cameras.length - 1];

    // Create stream and get video track
    navigator.mediaDevices.getUserMedia({
      video: {
        deviceId: camera.deviceId,
        facingMode: ['environment', 'user'],
        height: {ideal: 1080},
        width: {ideal: 1920}
      }
    }).then(stream => {
      const track = stream.getVideoTracks()[0];

      //Create image capture object and get camera capabilities
      const imageCapture = new ImageCapture(track)
imageCapture.getPhotoCapabilities().then(capabilities => {
 
        //let there be light!
        var isTorchOn  = false;
        const btn = document.querySelector('.switch');
        // if (capabilities.torch){
          btn.addEventListener('click', function(){
            isTorchOn = !isTorchOn;
            log("El flash esta encendido?: " + isTorchOn)
            try{
                track.applyConstraints({
                advanced: [{torch: isTorchOn}]
              });
            } catch(err){
                    log(err);
            }
          });

        const btn2 = document.querySelector('.switchOff');
        if (!capabilities.torch){
            log("Precione habilitar y encender");
        }
          btn2.addEventListener('click', function(){
            try{
                track.applyConstraints({
                advanced: [{torch: false}]
              });
            } catch(err){
                    log(err);
            }
          });

      });
    }).catch(log);
  }).catch(log);
  
const msg = document.getElementById("msg");
const button = document.getElementById("toggle");
let interval = null;
button.onclick = () => {

  if (interval) {
        clearInterval(interval);
        interval = null;
    }
    const seq = [];
    ["x02", ...msg.value, "n", "x03"].forEach(c => seq.push(...encode(c.charCodeAt(0))));
    interval = setInterval(() => {
        if (!seq.length) {
            clearInterval(interval);
            interval = null;
        } else if (seq.shift()) {
          try{
            track.applyConstraints({
                advanced: [{torch: isTorchOn}]
              });
            } catch(err){
                    log(err);
          }
        } else {
          try{
                track.applyConstraints({
                advanced: [{torch: false}]
              });
            } catch(err){
                    log(err);
            }
        }
    }, 50);

    function parity(val) {
    val = val ^ (val >> 1);
    val = val ^ (val >> 2);
    val = val ^ (val >> 4);
    return val & 1;
}

function encode(char) {
    const bits = [1];
    for (var i = 0x80; i > 0; i >>= 1) {
        bits.push(char & i ? 1 : 0);
    }
    bits.push(parity(char));
    bits.push(0);
    return bits;
}}}
</script>
</head>
<body>
    <button class="switch">Encender / Apagar</button> - 
    <button class="switchOff">Apagar</button>
    <h2>
    Console output
    </h2>
    <div id="console">Precione habilitar y encender</div>
</body></html>

When you click on turn On / Off the torch turns on, but I need that when a user enters a message or a number in the textbox a sequence is turned on when pressing accept. It should be clarified that this program only works in Chrome

Construct object wit array

I have a array of objects:

const arr = [
  {
    name: "Name 1",
    symbol: "S1"
  },
  {
    name: "Name 2",
    symbol: "S2"
  },
]

And I want to transform this on this

{
  S1: "Name 1", S2: "Name 2"
}

I tried this

arr.map((a) => { [a.symbol]: a.name })

But no luck. How can I achieve this?

how to change the download directory/location in pipe() method?

this code downloads the files in the project folders, how do i change this to another location?

await new Promise((resolve, reject) => {
    let fileExt = post.url.split(".").pop();
    request(`${post.url}`)
      .pipe(
        fs.createWriteStream(
          `${post.title.slice(0, 10).replace(/ +/g, "")}.${fileExt}`
        )
      )
      .on("finish", () => {
        console.log("download success..!");
        resolve();
      })
      .on("error", (error) => {
        console.log("from event ===>", error);
        rejects(error);
      });
  });

jquery submit form and stay on same page not working

The below code is supposed to submit the form and stay on the current page. It does submit the form, but it doesn’t stay on the same page as it redirects to the form processing page. I have tried using event.preventDefault(); and return false; – but neither are stopping the redirect. I tried them one at a time then added both at the same time and at different locations in the functin, but the redirect still happens.

  function submitForm() {
    var $subForm = $('#signupForm')[0] ;
    if (!$subForm.checkValidity()) {
      $subForm.find(':submit').click() ;
      return ;
    }
    
    $subForm.submit(function(event){
      event.preventDefault(); // not working  here
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
        console.log(response) ;
      },'json');
      return false;  // not working here
    });
    return false ;  // not working here
  }

My form is defined as:

<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
    ....
    <button type="button" onclick='submitForm();' id="ccInfoButton" style="" class="btn btn-primary buttonSignup" disabled >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>

Shouldn’t using spread syntax not reference the original array?

I have an Object array in my state called names, i’m trying to make a copy of this array to another Object array in state called shuffledNames, but when i shuffle the shuffledNames using the code below, the original names changes the ids to match the new shuffled ids. See images below for an example. I’ve tryed using .concat(), .slice(). I do not know what to try anymore.

  handleSort = () => {
    let tempName = [...this.state.names];

    let shuffledNames = tempName;

    for (let i = shuffledNames.length; i-- > 1; ) {
      let j = Math.floor(Math.random() * i);
      let temp = shuffledNames[i];
      shuffledNames[i] = shuffledNames[j];
      shuffledNames[j] = temp;
    }

    shuffledNames.forEach((shuffledName, index) => {
      shuffledName.id = index;
    });

    this.setState({ shuffledNames: shuffledNames });
  };

This is my state before shuffling

This is my state after shuffling

how to i stop the ccs keyframe from playing when the website loads and only play when i press the button

I want to make it so the text slide in animation doesn’t play on the website load and only plays when the button is pressed. also i am unsure why the text moves lower when the button is pressed.

i have tried using java script as one of the other questions suggested which allowed the button to work but then the problem uccured where the text goes a bit lower whne the button is pressed and im not sure why.

.textbox-1{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    flex-direction: column;
    right: 5%;
    top: 120%;
    position: absolute;
    animation-name: slide-right;
    animation-duration: 2s;
    height: 400px;
    width: 1750px;
    color: #c9cecd;
}

@keyframes slide-right{
    from{
        opacity: 0.1;
        right: 25%;
    }
    to {
        opacity: 1;
        right: 5%;
    }
    
}
 <div class="background">
            <div id="BUTTON" >

              <button type="button" onclick="ani()" value="Click"><span></span>Rules</button>
                
                  



<script>
function ani() {
  document.getElementById('textbox-1').className = 'textbox-1';
}
</script>
         

            </div>
            
                    <div class="textbox-1" >



              

                    <p id="textbox-1" style="font-family:courier;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br>
<br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br>
<br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br>
<br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br>
<br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br>
<br>

font awsome icons didn’t changing

  <div >
    <i id="icons" class="far fa-heart"></i>
  </div>

I don’t know why this code doesn’t changes the icons as script is linked and the console didn’t show any error as well

 let icons= document.getElementById('icons');
    icons.addEventListener('click', ()=>{
      icons.classList.remove=("far fa-heart");
      icons.classList.add=("fas fa-heart");
      console.log(icons)
    })

Vue: two params in url not loading correct route

Comunity

I have a list of bookings (component: BookingListItem), which I render in my component “BookingView”. Now I want to show the booking details when I click on one of these booking items.
For this, I created a streched link, like that:

<router-link
      :to="`patients/${this.user.id}/bookings/${booking.booking_id}`"
      class="stretched-link"
    ></router-link>

I need the userid and the bookingid to make an api call from the ReadBookingView component (in this component the bookingdetails are displayed).

In my router.js file I defined the route like that:

    {
      path: "/patients/:userid/bookings/:bookingid",
      name: "readbooking",
      component: ReadBookingView,
    },

But when I load my BookingView component the following warnings are showed: enter image description here
There the userid and the bookingid are correct. But when I click on one of my booking items the following link is opened: http://URL:8081/4328

I hope y’all understand my explanation. Cause I don’t understand why it’s not loading correcty and I am very grateful for all your inputs.

Why does a variable with .substring() not reflect css styling?

Using pure javascript, I am trying to create a price-validating function that when used, validates prices entered into a form. There are 4 requirements to my validation:

  1. Input must be a number and cannot be empty
  2. If a decimal is entered, there must at least be 1 pre- and post-decimal character
  3. Price entered must be a number that is between $1 and $99.99 (both inclusive)
  4. Price entered must not have whitespaces in between

and here is my code:

function formCheck() {
  var success = true; //default, assumes client enters all fields correctly so "process.html" will load
  var msgBox = document.getElementById('divMessage'); //feedback div

  //Price Variables
  var movPrice = document.getElementById('txtPrice');
  var priceFdBk1 = '<ul><li> Please enter <b>numbers</b> only. </li></ul>';
  var priceFdBk2 =
    '<ul><li> You entered a decimal point. Please enter a <b>number</b> both before and after the decimal place. </li></ul>';
  var priceFdBk3 = '<ul><li> Please enter a movie price between $1.00 to $99.99 (up to 2 decimal places). </li></ul>';
  var priceFdBk4 = '<ul><li> Please do not leave a space when entering the movie price. </li></ul>';

  //Price Validation
  function priceCheck(price, fdBk1, fdBk2, fdBk3, fdBk4) {
    //arguments = price and feedbacks if errors are made
    var price_clean = price.value.trim(); //price entered by client without whitespace
    var price_len = price_clean.length; //number of characters in price entered

    //If there is a $ sign, remove it first
    var dollarSensor = price_clean.charAt(0);
    if (dollarSensor == '$') {
      price_clean = price_clean.substring(1);
    }

    //If there is a decimal point, obtain pre- and post-decimal characters
    if (price_clean.indexOf('.') > -1) {
      var deciSensor = 1; //remember that input has a decimal
      var intValue = price_clean.split('.')[0]; //obtain pre-decimal characters)
      var decimalValue = price_clean.split('.')[1]; //obtain post-decimal characters
      var postCounter = 0;
      for (var j = 0; j < decimalValue.length; j++) {
        //count number of decimal places
        postCounter += 1;
      }
    }

    //Filter 1: Input must be a number and cannot be empty
    if (isNaN(price_clean) || price_clean == '') {
      msgBox.innerHTML = fdBk1;
      price.className = 'yellow';
      success = false;
    }

    //Filter 2: If a decimal is entered, there must at least be 1 pre- and post-decimal character
    else if ((deciSensor == 1 && intValue == '') || (deciSensor == 1 && decimalValue == '')) {
      //if client did not enter a number before and after the decimal point
      msgBox.innerHTML = fdBk2;
      price.className = 'yellow';
      success = false;
    }

    //Filter 3: Price entered must be a number that is between $1 and $99.99 (both inclusive)
    else if (price_clean < 1 || price_clean > 99.99 || postCounter > 2) {
      msgBox.innerHTML = fdBk3; //message in feedback div
      price.className = 'yellow';
      success = false; //prevent loading of "process.html" since selected movie is invalid
    } else {
      price.className = 'transparent';
    }

    //Filter 4: Price entered must not have whitespaces in between
    for (var i = 0; i < price_len; i++) {
      oneDigit = price_clean.charAt(i);
      if (oneDigit == ' ') {
        //if the price float character has a whitespace
        msgBox.innerHTML = fdBk4; //message in feedback div
        price.className = 'yellow'; //highlight error in client's input
        success = false; //prevent loading of "process.html" since selected movie is invalid
      } else if (oneDigit == '') {
        //if the price float character has no whitespace
        price.className = 'transparent'; //remove highlight from client's input
      }
    }
  }
  priceCheck(movPrice, priceFdBk1, priceFdBk2, priceFdBk3, priceFdBk4);

  return success;
}
.yellow {
  background-color: yellow;
}

.transparent {
  background-color: transparent;
}

h1 {
  color: #7157ff;
}

hr {
  display: block;
  border: 0;
  border-top: 3px solid #f90;
  padding: 0;
}

textarea {
  width: 70%;
}

#div_main {
  font-family: Sans-serif;
  margin: auto;
  margin-top: 30px;
  width: 500px;
}

#div_left {
  width: 150px;
  display: inline-block;
  float: left;
}

#div_left p {
  margin-bottom: 19px;
}

#div_right {
  width: 350px;
  display: inline-block;
  float: right;
}

.clear {
  clear: both;
}
<div id="div_main">
  <h1>
    Add Movie
  </h1>
  <hr>
  <form action="process.html" method="POST">
    <div id="div_left">
      <p>Price* ($):</p>
    </div>
    <div id="div_right">
      <p><input type="text" id="txtPrice" name="txtPrice"></p>
    </div>
    <input type="submit" id="btnSubmit" onclick="return formCheck()">
  </form>
  <div id="divMessage">
    *denotes compulsary fields.
  </div>
</div>

The code works fine but has 1 issue, which I suspect comes from this line:

price_clean = price_clean.substring(1)

Specifically, whenever I enter a “$” sign into the form, my code will remove the “$” sign and validate the input as usual. However, when the input is invalid, it no longer highlights the input box in yellow.

May I know what is going on and how can this be fixed using vanilla javascript? Thank you

How can we write (req, res, function) in this way in javascript

Hi I’m trying to make a register route in my page using passport. What I can’t understand is

What passport.authenticate(“local”)(req,res,function(){}) is

I understand passport.authenticate(“local”) is by using local strategy, we judge id/password is right or not. But I have no idea how (req,res, function(){}) after that part works. How can we write like that?

+) “User” in the code is just a model name.

app.post(“/register”, function(req,res){ 
User.register({username:req.body.username}, 
req.body.password, function(err,user){

  if (err) {
    console.log(err);
    res.redirect(“/register”);
    }else{
    passport.authenticate(“local”)(req,res,function(){
      res.redirect(“/secrets”);
});

multiple query-string in react router v6

I want to use two query strings in my URL
when it has both filter=done and search=something
I want to show in URL localhost3000/?filter=done&search=something
but it overwrites one of them and shows only one.
I use HOC to pass the location and navigate to my class component.
this is my code:

class TodoList extends Component {
  constructor(props) {
    super(props);
    const { filter } = queryString.parse(this.props.location.search, {
      ignoreQueryPrefix: true,
    });
    const { search } = queryString.parse(this.props.location.search, {
      ignoreQueryPrefix: true,
    });
    this.searchParams = {
      filter: filter || "all",
      search,
    };
    this.state = {
      todolist: [],
      addtodo: "",
      searchterm: "",
      searchtodolist: [],
      filter: "",
    };
  }

when I click to filter the list, this function is calls

 handleFilter = (value) => {
        this.setState(
          {
            filter: value,
          },
          () => this.replaceUrlFilter()
        );
      };
  replaceUrlFilter = () => {
        this.props.navigate(
          this.state.filter === "all" ? "/" : `?filter=${this.state.filter}`
        );
      };

when I search something in search input, this function is calls

handleSearch = (event) => {
    this.setState(
      {
        searchterm: event.target.value,
      },
      () => this.replaceUrlSearch()
    );
  };
 replaceUrlSearch = () => {
    this.props.navigate(
      this.state.searchterm === "" ? "" : `?search=${this.state.searchterm}`
    );
  };