Changing read only input field text according to radio button selection

the scenario is that i want to set the total price based on user choice of radio buttons, when user chooses one of the radio buttons the price changes accordingly.

here is the the HTML:

        <div class="input_box">
            <h4 style="text-align: center;">إختر الباقة</h4>
            <input type="radio" name="package" class="radio" id="pk1" value="70">
            <label for="pk1">بالساعة</label>
            <input type="radio" name="package" class="radio" id="pk2" value="200">
            <label for="pk2">يوم</label>
            <input type="radio" name="package" class="radio" id="pk3" value="2500">
            <label for="pk3">شهر</label>
        </div>
        <div class="input_box">
            <input type="number" placeholder="Total Value" name="price" class="name" id="output">
            <i class="fa fa-money icon" aria-hidden="true"></i>
        </div> 

i tried to use javaScript solution such as:

        <script>
            document.getElementsByName("package").addEventListener("change", function(){
                document.getElementById("output").innerHTML = this.value;// Show the value in output element

        });
        </script>

but it seems nothing works for me, i appreciate any help, Thank you 🙂

subproperty of an object isn’t updated

I’m receiving an object through props yet when a subproperty (exp: this.myObj.user.active) of that object is updated the changes aren’t considred unless I make a hard reload or I lougout and reconnect to the app (btw isn’t the init method supposed to check for changes and therefore refresh of the data ?)

  props: {
    myObj: {
      type: Object,
      default: null,
    },
  },
    init() {
      if (this.myObj) {
        return this.$service.myMethod(this.myObj)
          .then(() => this.test = this.val);
      } 
    },

here is the needed method

    check() {
      if (this.myObj) {
     // do something
    },

when I debug the app I can see the parameter this.Obj is maintaining an old value of active on the init and also on check method

how to solve this problem ?

How do I know if code is asynchronous or not

I wrote an async-await functions using Promise returning functions. However, I’m not sure if the behavior I desire is being implemented. On that token, I’ve tried researching ways to see if my code is behaving asynchronously but to no avail. Without further ado, here is my code :

sum = 0

function checkEven(num) {
    return new Promise((res,rej) => {
        if(typeof num === 'number'){
            if(num % 2 == 0){
                res(true)
                console.log(`Currently processing ${num}`)
            } else {
                res(false)
            }
        } else {
            rej(`${num} is not a number!`)
        }
    })
}

function addToSum(bool, num) {
    return new Promise((res,rej) => {
        if(bool){
            sum += num
            res(`Adding ${num} to sum. Sum is now ${sum}.`)
        }else{
            res(`Not adding ${num} to sum. Sum is now ${sum}.`)
        }
        rej("hi")
    })

}

async function addEvenNumbersOnly(n1,n2) {
    try{
        const first = await checkEven(n1)
        const second = await checkEven(n2)
        const addFirst = await addToSum(first, n1)
        console.log(addFirst)
        const addSecond = await addToSum(second, n2)
        console.log(addSecond)
        console.log(sum)
    } catch (err){
        console.log(err)
    }
    
}

addEvenNumbersOnly(100,102)

Hopefully the code is self explanatory; I take two numbers and check their evenness, if they’re even I add them to a global sum, otherwise I don’t.

The asynchronous behavior in my head is here:

const first = await checkEven(n1)
const second = await checkEven(n2)

Does checkEven(n2) execute while checkEven(n1) is being processed?

const addFirst = await addToSum(first, n1)
const addSecond = await addToSum(second, n2)

Similarly, does addToSum(second, n2) start execution while addToSum(first, n1) is being executed?

drag and drop guidelines

I’m trying to implement drag and drop guidelines

example image

I have an array with objects, and with a for loop and Recursive Component in react which display the data.

JSON example:

[
    {
        "height": "100",
        "width": "100",
        "left": "0",
        "top": "0",
        "children":[
            {
                "height": "100",
                "width": "200",
                "left": "50",
                "top": "60"
            }
        ]
    },
    {
        "height": "100",
        "width": "200",
        "left": "20",
        "top": "30"
    }
]

when the user drags an element, I want to show some guidelines based on other draggable objects which are present in the view.

I have an idea to use an event listener and every time the mouse position changes when the user drags an element, check every draggable object and then display guides, but this is not an optimized way to do this.

any idea how to solve this challenge?

How do i hide a Modal after clicking a button within the Modal to display another Modal?

I want the data-modal=”create-wager” to close after I click the button id=”createLobby” while simultaneously displaying the data-modal=”pending-transaction”. Currently the way it is displayed just overlaps the Create-Wager modal. I tried to use scripts in the ejs file to no luck. Any direction would help a lot!

The HTML

<div class="modal__overlay" data-modal="create-wager">
  <div class="modal">
    <div class="modal__close" data-close></div>
    <h2 class="modal__title">CREATE WAGER</h2>
    <form action="/lobby" method="POST" data-form="create-room">
      <div class="form__group--styled">
        <h3 class="form__label">Game</h3>
        <div class="flex flex-evenly flex-wrap">
          <% if (locals.gameData.length) { %> <% for (var i = 0; i <
          gameData.length; i++) { %>
          <label class="custom-radio"
            ><%= gameData[i].name %> <input type="radio" value="<%=
            gameData[i].identifier%>" name="game" <% if(i == 0) { %> checked <%
            } %> >
            <span class="checkmark"></span>
          </label>
          <% } %> <% } %>
        </div>
      </div>
      <div class="form__group--styled">
        <h3 class="form__label">Currency</h3>
        <div class="modal__crypto-container">
          <% if (locals.cryptoData.length) { %> <% for (var i = 0; i <
          locals.cryptoData.length; i++) { %>
          <label class="custom-radio"
            ><%= cryptoData[i].symbol %> <input type="radio" name="currency"
            value="<%= cryptoData[i].symbol %>" <% if(i == 0) { %> checked <% }
            %> >
            <span class="checkmark"></span>
            <img
              class="modal__crypto-icon"
              src="<%= cryptoData[i].image %>"
              alt="<%= cryptoData[i].symbol %>"
            />
          </label>
          <% } %> <% } %>
        </div>
      </div>
      <div class="form__group--styled">
        <h3 class="form__label">Amount</h3>
        <input
          class="form__number-input"
          type="number"
          name="amount"
          value="1"
          step="0.000001"
          min="0.000001"
          id="wagered-amount"
        />
      </div>
      <div class="form__group--styled">
        <!-- <h3 class="form__label">Game ID</h3> -->
        <input
          class="form__number-input"
          name="id"
          id="game-id"
          type="hidden"
        />
      </div>
      <div class="form__group--styled" >
        <button
          type="clickable"
          class="button button--wide modal__button"
          data-toggle="pending-transaction"
          data-dismiss="createWager"
          id="createLobby"
        >
          Create Room
        </button>
      </div>
    </form>
  </div>
</div>

<div class="modal__overlay" data-modal="pending-transaction">
  <div class="modal">
    <div class="modal__close" data-close></div>
    <form action="/lobby" method="POST" data-form="pending-transaction">
      <h3 class="form__label">Pending Transaction... This will Only Take a Few Seconds.</h3>
    </form>
  </div>

</div>

How many nines? Codewars

https://www.codewars.com/kata/5e18743cd3346f003228b604

i am working on this task – “How many Integers in the range [0..n] contain at least one 9 in their decimal representation?”.
My function passed all test but final output is “Execution Timed Out (12000 ms)” what probably means that my function algorithm is inefficient. What’s wrong there? Appriciate any help.

function nines(n) {
    let amountOfNines = 0;

    for (let i = 0; i <= n; i++) {
        if (/9/.test(i)) amountOfNines++;
    }

    return BigInt(amountOfNines);
}

Reordering array using .sort with parameters

I have a function to reorder an array with objects inside and I call that function with the object property I want to sort, but I don’t know how to set the callback function to use the parameter. I tried use eval() but with no success.

function order(param){
  const newOrder = arrayContent.sort((first,second) => eval(`${first}.${param}`) > eval(`${second}.${param}`) ? 1 : -1);
  console.log(newOrder);
};
order('name')

responsive nav not toggling when i click the icon

I need the margin and width functions to work so i can proceed to the styling. I await your kind rsponses, thank you very much.

 <nav class="navbar">
        <span class="open-slide">
            <a href="#" onclick="openSlideMenu()">
                <i class="fas fa-bars"></i>
            </a>
        </span>
       
    </nav>
    <div id="slide-menu" class="side-nav">
        <a href="#" class="btn-close" onclick="closeSlideMenu()">&times;</a>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Services</a>
        <a href="#">FAQ</a>
        <a href="#">Lgout</a>
    </div>
    <div id="main">
        <h2>A responsive slide bar</h2>
    </div>


    <script>
        function openSlideMenu() {
            document.getElementById("slide-menu").style.width = "250px";
            document.getElementById("main").style.marginLeft = "250px;"
        }
        function closeSlideMenu() {
            document.getElementById("slide-menu").style.width = "0";
            document.getElementById("main").marginLeft = "0";
        }
    </script>

How can I convert string into an imported alias in React?

I have got an image folder that contains images of playing cards and I imported them as follow:

import D2 from "../image/D2.png";
import H2 from "../image/H2.png";
import S2 from "../image/S2.png"; 

and all the way until I reach SA (Spade Ace)

I also have key value pair dictionary such as:

  1: "C2",
  2: "D2",
  3: "H2",
  4: "S2",... 

I need this dictionary to both calculate the rank of the card and to generate image.

atm I can retrieve the value by evaluating the last char of the string and convert it into int (in case of K,Q etc I have a switch case for them)

My issue is I have trouble to convert the string into the alias that I imported.
I tried doing eval(4) but it didn’t work.

if I modified the dictionary into

  1: C2,
  2: D2,
  3: H2,
  4: S2,...

I can easily use this as the src of my images, but I can no longer use the card-code to obtain the value of the card.

Could you please suggest a solution or a better approach for this problem.

Experiencing strange recursion behavior with setTimeout

I wrote a simple 3d flood-filling algorithm to draw a diamond shape into an array (that array is pseudo multi dimensional as described in this post). The actual method looks like this:

/**
 * Draws a 3d diamond shape into an array using a flood fill algorithm.
 *
 * @param data The array to "draw" the diamond shape in. Must be of length 100 * 100 * 100 and all values must be 0.
 * @param pos Tupel of x, y, z position to be the center of the diamond.
 */
 export function flood3dDiamondShape(data: Uint8Array, pos: [number, number, number], distance = 0): void {
    if (distance > 10) {
        return;
    }

    const [x, y, z] = pos;
    const index = (x) + (z * 100) + (y * 100 * 100);
    if (data[index] > 0) {
        return;
    }

    data[index] = 1;

    flood3dDiamondShape(data, [x + 1, y, z], distance + 1);
    flood3dDiamondShape(data, [x - 1, y, z], distance + 1);
    flood3dDiamondShape(data, [x, y + 1, z], distance + 1);
    flood3dDiamondShape(data, [x, y - 1, z], distance + 1);
    flood3dDiamondShape(data, [x, y, z + 1], distance + 1);
    flood3dDiamondShape(data, [x, y, z - 1], distance + 1);
}

However, this doesn’t result in the expected result but draws a strangely shaped “blob” into the array (refer to image 2). I tried to debug that behavior by wrapping the six calls to flood3dDiamondShape(...) into a setTimeout callback. It looks like this:

setTimeout(() => {
    flood3dDiamondShape(data, [x + 1, y, z], distance + 1);
    flood3dDiamondShape(data, [x - 1, y, z], distance + 1);
    flood3dDiamondShape(data, [x, y + 1, z], distance + 1);
    flood3dDiamondShape(data, [x, y - 1, z], distance + 1);
    flood3dDiamondShape(data, [x, y, z + 1], distance + 1);
    flood3dDiamondShape(data, [x, y, z - 1], distance + 1);
}, 1);

This still works but now the strange “blob” isn’t there anymore. It now is the expected diamond shape as you may see in image 3.

Note that using the second method I of course waited for the algorithm to finish before actually drawing the shape.

The question now actually is: Why am I experiencing this behavior? I would like to get the diamond shape 3 but without using setTimeout.

How it is supposed to look (with setTimeout)

How it actually looks (without setTimeout)

How to get specific key and value from a long json object while iterating it in node.js

I am trying to parse a csv file in node.js , i am able to parse the csv file and can print the content , the contents are coming as a from of a json object.Now my target is to iterate the json object and take out specific key and values from each block and use them in a Query which will do some DB operations.But the problem is while i am trying to iterate the json only first key and values of the first block is printed. Let me post the code what i have done

 fs.createReadStream(path)
  .pipe(csv.parse({headers:true ,ignoreEmpty : true}))
  .on("error",(error) => {
   throw error.message;
   })
   .on("data",function(data){
    if(data && data!=={}){
    Object.keys(data).forEach(function(k){
     if(k==='name' || k==='Office'){
    let selectQury = `select name,Office from myTable where  name = ${data['name']} and Office 
    =${data[Office]};
    db.query(selectQury,(err,res)=>{
     if(err){
      console.log('error',null);

This my json which i parse from the csv looks like

  {
    id:1,
    name:"AS",
    Office:"NJ"
    ........
    ACTIVE: 1.
  },
   {
    id:2,
    name:"AKJS",
    Office:"NK"
    ........
    ACTIVE: 2.
  }

so now what i want is in the select Query the parameters will be passed like

 let selectQury = `select name,Office from myTable where  name = "AS" and Office  = "NJ"; 
 in the first iteration
 let selectQury = `select name,Office from myTable where  name = "AKJS" and Office = "NK";  
 in the second iteration and so on as the csv grows.

I am not able to do it ,please help . Thanks in advance. I am new to node.js & tricky javascript operations.

render declaration for map in javascript

I try to add @googlemaps/react-wrapper in my project,
following this explaination : https://developers.google.com/maps/documentation/javascript/react-map
But at the first instruction i have this,

const render = (status: Status) => {
  return <h1>{status}</h1>;
};

and if i really understand it is TypeScript and my project page is in javascript,
how to do the same thing in javascript ?
hope that it’s not a too much stupid question. thanks by advance

Mitigate user removing required field from form

I have a few forms for signing in/up or continuing as guest using the firebase. I want the user to be forced to put in an email so I can identify the user when they come to pick up their order and send them a receipt after they’ve paid. There is nothing preventing the user from just inspecting element and removing the required field, and the firebase functions are called from the front end so I cant even use my server to double check there is an email.

Is there a way to mitigate this? Aside from Firebase specific solutions, is there a way to mitigate this issue with all required fields? There is obviously a way as other websites implement this but I’m not sure how

Maybe run a script to check if the required attribute has been removed but that too can be deleted or edited.