javascript – Auto fill input based on select dropdown in Vue JS

I’m looking solution for how to auto fill input in vue js. I have a form which consists of input type text, select dropdown, quantity, etc. I want when the select dropdown is selected, then the quantity of vCPU, vRAM, and quantity will be automatically filled with the value according to the selected Package type.

I’m confused, to put the if conditional in the <base-quantity> at the @updateQuantity custom event or in v-if attribute. Is there anyone here that can help me solve this problem?

The full source code is in this codesandbox => https://codesandbox.io/s/suspicious-almeida-rjyy9

<template>
  <div class="container-fluid">
    <h2>Storage</h2>
    <div class="row">
      <div class="col-12">
        <form @submit.prevent="submitFormStorage">
          <div class="form-group">
            <label for="">Server Name</label>
            <input type="text" name="name" class="form-control" v-model="serverName" />
          </div>
          <div class="form-group">
            <div for="formGroupExampleInput">Specification</div>
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                name="storage-type"
                :value="specifications(0).name"
                @change="setSpecification"
                id="custom"
              />
              <label class="form-check-label" for="custom">custom</label>
            </div>
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                name="storage-type"
                :value="specifications(1).name"
                @change="setSpecification"
                id="pool"
              />
              <label class="form-check-label" for="pool">Pool resource</label>
            </div>
          </div>
          <div class="form-group mb-3">
            <div class="form-group-label">
              <label class="form-group-text" for="package-type">Package</label>
            </div>
            <select
              class="custom-select"
              id="package-type"
              v-model="selectedPackage"
            >
              <template v-for="data in storagePackage" :key="data.name">
                <!-- <option selected>Choose...</option> -->
                <option :value="data.value">
                  {{ data.name }}
                </option>
              </template>
            </select>
          </div>
          <h6>Components</h6>
          <div class="row">
            <div class="col-6">
              <div class="form-group">
                <div for="formGroupExampleInput">vCPU (GHz)</div>
                <base-quantity
                  @updateQuantity="updateCpu"></base-quantity>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <div for="formGroupExampleInput">vRAM (Gb)</div>
                <base-quantity
                  @updateQuantity="updateRam"></base-quantity>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <div for="formGroupExampleInput">Capacity</div>
                <base-quantity
                  @updateQuantity="updateCapacity"></base-quantity>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <div for="formGroupExampleInput">Server Qty</div>
                <base-quantity
                  @updateQuantity="updateServer"></base-quantity>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-6">
              <div class="form-group">
                <label for="formGroupExampleInput">Storage Type</label>
                <select name="database" id="" class="form-control" v-model="selectedStorageType">
                   <option v-for="storage in storages" :key="storage.name" :value="storage.value">{{ storage.name }}</option>
                </select>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <label for="formGroupExampleInput">OS</label>
                <select name="database" id="" class="form-control" v-model="selectedOs">
                   <option v-for="o in os" :key="o.name" :value="o.value">{{ o.name }}</option>
                </select>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <label for="formGroupExampleInput">Database</label>
                <select name="database" class="form-control" v-model="selectedDatabase">
                  <option v-for="database in databases" :key="database.name" :value="database.value">{{ database.name }}</option>
                </select>
              </div>
            </div>
            <div class="col-6">
              <div class="form-group">
                <label for="formGroupExampleInput">Firewall</label>
                <select name="database" id="" class="form-control" v-model="selectedFirewall">
                   <option v-for="firewall in firewalls" :key="firewall.name" :value="firewall.value">{{ firewall.name }}</option>
                </select>
              </div>
            </div>
          </div>
          <div class="form-group mt-4">
            <button class="btn btn-primary btn-block" @click.prevent="addToCart">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import BaseQuantity from "../base/BaseQuantity.vue";
export default {
  components: {
    BaseQuantity,
  },
  data() {
    return {
      specification: '',
      serverName: '',
      databases: (
        {
          name: "DB 1",
          value: 100
        },
        {
          name: "DB 2",
          value: 120
        }
      ),
      specifications: (
        {
          name: 'Custom',
          value: 200
        },
        {
          name: 'Pool',
          value: 100
        }
      ),
      storages: (
        {
          name: "storage 1",
          value: 100
        },
        {
          name: "storage 2",
          value: 120
        }
      ),
      os: (
        {
          name: "os 1",
          value: 100
        },
        {
          name: "os 2",
          value: 120
        }
      ),
      firewalls: (
        {
          name: "firewall 1",
          value: 100
        },
        {
          name: "firewall 2",
          value: 120
        }
      ),
      storagePackage: (
        {
          name: "One",
          value: 30,
        },
        {
          name: "Two",
          value: 40,
        },
        {
          name: "Three",
          value: 50,
        },
      ),
      quantity: 0,
      duration: 0,
      selectedStorageType: "",
      selectedPackage: "",
      selectedDatabase: "",
      selectedFirewall: "",
      selectedOs: "",
      selectedStorage: "",
    };
  },
  watch: {
    serverName: function() {
      this.$store.commit('setServerName', this.serverName);
    },
    selectedPackage: function() {
      let pack = this.storagePackage.find((pack) => pack.value == this.selectedPackage);
      this.$store.commit('setPackage', pack);
    },
    selectedOs: function() {
      let os = this.os.find((os) => os.value == this.selectedOs);
      this.$store.commit('setOs', os);
    },
    selectedFirewall: function() {
      let firewall = this.firewalls.find((firewall) => firewall.value == this.selectedFirewall);
      this.$store.commit('setFirewall', firewall);
    },
    selectedDatabase: function() {
      let database = this.databases.find((database) => database.value == this.selectedDatabase);
      this.$store.commit('setDatabase', database);
    },
    specification: function() {
      let specification = this.specifications.find((specification) => specification.name == this.specification);
      this.$store.commit('setSpecification', specification);
    },
    selectedStorageType: function() {
      let storage = this.storages.find((storage) => storage.value == this.selectedStorageType);
      this.$store.commit('setStorageType', storage);
    }
  },
  methods: {
    async addToCart() {
      let isEmpty = await this.$store.dispatch('isEmpty');
      if(!isEmpty) {
        this.$store.commit('calculateStorageCost');
        this.$store.commit('setStorage', this.$store.getters.getStorageState);
      }
    },
    updateCpu(val) {
      this.$store.commit('setCpu', {qty: val, value: 100});
    },
    updateRam(val) {
      this.$store.commit('setRam', {qty: val, value: 100});
    },
    updateCapacity(val) {
      this.$store.commit('setCapacity', {qty: val, value: 100});
    },
    updateServer(val) {
      this.$store.commit('setServer', {qty: val, value: 100});
    },
    updateDuration(val) {
      this.duration = val;
    },
    setSpecification(event) {
      this.specification = event.target.value;
    }
  },
};
</script>

javascript – Calculate max and average of paginated JSON API result

I have this JSON:

var myJSON = (
{
  "page": 1,
  "totalPages": 5,
  "data": ({
    "title": "Movie 1",
    "rating": 4.7
}, {
    "title": "Movie 2",
    "rating": 7.8
})

}, {
  "page": 2,
  "totalPages": 5,
  "data": ({
    "title": "Movie 3",
    "rating": 5.1
  }, {
    "title": "Movie 4",
    "rating": 2.4

})
});

I need to calculate average and max rating.

From my perspective this should use map and reduce for this purpose, but, I’m not sure if the JSON has the right format, or if it needs any sanitization.

I’m using this code right now, but I get a weird string as an output:

var Max_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating > cur.rating)? acc : cur) );
var Min_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating < cur.rating)? acc : cur) );

var Avg_JSO = myJSON.reduce( (acc, cur, idx, arr )=> {
  let
    sum = acc.rating + cur.rating,
    no = idx +1;
  if (no === arr.length) { sum = sum / no };
  return { 'name': cur.name, 'rating': sum }
});

console.log ('max =', JSON.stringify(Max_JSO) );
console.log ('min =', JSON.stringify(Min_JSO) );

"max =", "{&quot;page&quot;:2,&quot;totalPages&quot;:5,&quot;data&quot;:({&quot;title&quot;:&quot;Movie 3&quot;,&quot;rating&quot;:5.1},{&quot;title&quot;:&quot;Movie 4&quot;,&quot;rating&quot;:2.4})}"

Is there any way to do this better?

Also, I need to not only read rating from data key, but also outside of it, as you can see on var myJSON

javascript – How to randomly allocate values for fixed sum columns and rows?

How to solve this type of problem?
Where:

  1. total row sum;
  2. total col sum;
  3. grand total;
  4. total rows 10;
  5. total cols 10;
  6. maximum possible grand total 20 (sum of total rows OR total colums, always equal);
  7. allocated values must be >= 0;

Result:
Randomly allocated row and col totals to cells.

PROBLEM (sample with 3×3 but should be for 10×10)

     c1  c2  c3  total
r1    ?   ?   ?   2
r2    ?   ?   ?   1
r3    ?   ?   ?   0
total 2   1   0   3(grand total)

SOLUTION

      c1  c2  c3  total
r1    2   0   0   2
r2    0   1   0   1
r3    0   0   0   0
total 2   1   0   3(grand total)

My approach: didn’t come up with any sensible method.

Thank you for your effort.

javascript – Como utilizar funções de JS dentro de um processo server-side de PHP?

Primeiramente, peço a compreensão a todos, pois estou voltando agora a utilizar a plataforma, e não tenho tanto experiência em desenvolvimento…


Estou exibindo os dados do meu banco de dados MySQL em uma DataTables via server-side.

Recentemente, estava olhando o DataTables Editor e vi algumas opções muito interessantes e práticas, e comecei a pesquisar exemplos semelhantes, para eu implementar em meu código, pois, infelizmente o DataTables Editor é pago.

E estou lutando há 3 dias, para conseguir esse exemplo rodar em minha tabela.

O código que eu tenho até agora, é esse:

HTML:

// index.html

<table id="example" class="display" style="width:100%">
     <thead>
          <tr>
             <th>ID</th>
             <th>First name</th>
             <th>Last name</th>
             <th>Email</th>
             <th>Gender</th>
             <th>Country</th>
             <th>Created</th>
             <th>Status</th>
         </tr>
    </thead>    
</table>

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function(){
    $('#example').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax":{
          url :"processing_table.php",     // Aonde o json datasource vai ser carregado
          type: "post",                    // Método a ser enviado
        } 
    });
});

// Script edit inline 
function highlightEdit(editableObj) {
        $(editableObj).css("background","white");
    } 
    
    function saveInlineEdit(editableObj,column,id) {
        // no change change made then return false
        if($(editableObj).attr('data-old_value') === editableObj.innerHTML)
        return false;
        // send ajax to update value
        $(editableObj).css("background","white url(assets/images/loader.gif) no-repeat right");
        $.ajax({
            url: "salvar_dados_inline.php",
            cache: false,
            data:'column='+column+'&value='+editableObj.innerHTML+'&id='+id,
            success: function(response)  {
                console.log(response);
                // set updated value as old value
                $(editableObj).attr('data-old_value',editableObj.innerHTML);
                $(editableObj).css("background","#FDFDFD");         
            }          
       });
    }
</script>  

PHP (serverside):

// processing_table.php    

... 

// Fazendo loop e buscando dados
while($row = mysqli_fetch_array($query)){
    $subdata = array();

    $subdata() = $row(0); // 'id' do banco

    // 'first_name' do banco, estou tentando utilizar o script nesse campo!
    $subdata() = 
    "<td contenteditable='true' data-old_value=".$row(1)." onBlur="saveInlineEdit('this','first_name',".$row(0).";")' onclick="highlightEdit('this');">
        ". $row(1) . "
    </td>";

    $subdata() = $row(2); // 'last_name' do banco
    $subdata() = $row(3); // ...
    $subdata() = $row(4); // ...
    $subdata() = $row(5); // ...
    $subdata() = $row(6); // ... 
    $subdata() = $row(7); // ...         

    // Todos os valores em um array
    $data() = $subdata;
}

...

Página de update:

<?php
// salvar_dados_inline.php

require_once("conexaobd.php");

$sql = "UPDATE members set ".$_REQUEST("column")."='".$_REQUEST("value")."' WHERE id='".$_REQUEST("id")."'";
mysqli_query($con, $sql);

?>

Dessa maneira como meu code está, os dados estão sendo exibidos corretamente, o que NÃO está funcionando é o script.

  • Problema: Não acontece absolutamente nada, quando eu clico no campo “first_name”
    na DataTables, não tem nenhuma ação.
  • Tentei colocar o script na página processing_table.php, mas da erro e não carrega os dados.

Erro:

DataTables warning: table id=example – Invalid JSON response. For more
information about this error, please see http://datatables.net/tn/1

Alguém consegue me ajudar? agradeço desde já!

Javascript y firebase, tengo un problema ya que estoy tratando de configurar el botón eliminar pero, me está generando un error, el cual no he podido

Tengo una base de datos en firebase, y cargué los registros en una tabla a través de JavaScript en una aplicación web, al momento de presionar clic en el botón eliminar me genera un error y no me elimina el registro que seleccioné, el error lo genera específicamente al en ref() que está en la siguiente línea: firebase.database().ref(‘students/${uid}’).remove(), si yo le quito /${uid} me elimina todos los registros pero necesito eliminar solo el registro seleccionado. Agradezco su ayuda.

const deleteStudent = (Uid) => {
firebase.database().ref(‘students/${uid}’).remove()//ESTA ES LA PARTE QUE ESTÁ GENERANDO EL ERROR, NO ELIMINA EL SEGISTRO SELECCIONADO

}

window.addEventListener(‘DOMContentLoaded’, async(e) => {

await studentRef.on('value', (students) => {
    studentsTable.innerHTML = ``
    students.forEach(student => {
        let studentData = student.val()
        studentsTable.innerHTML += `<tr>
        
        <th>1</th>
        <td>${studentData.Documento}</td>
        <td>${studentData.Nombres}</td>
        <td>${studentData.Apellidos1}</td>
        <td>${studentData.Apellidos2}</td>
        <td>${studentData.Grado}</td>
        <td>${studentData.Jornada}</td>
        <td>${studentData.Rh}</td>
        <td>${studentData.Acudiente}</td>
        <td>${studentData.Direccion}</td>
        <td>${studentData.Zona}</td>
        
        <td>

        <button class="button is-warning" id="${studentData.Uid}">
            <i class="fas fa-pencil-alt" > </i>
        </button>
        <button class="button is-danger" id="${studentData.Uid}">
            <i class="fas fa-trash-alt " > </i>
        </button>

    </td>
    </tr>`
        const deleteButtons = document.querySelectorAll('.is-danger')
        deleteButtons.forEach((button) => {
            button.addEventListener('click', (e) => {
                deleteStudent(e.target.dataset.id)


            })
        })

    })
})

})
introducir la descripción de la imagen aquí

javascript – 2D moving objects in angle

Im making simple 2D space shooter with use of html5 and JavaScript.

The idea is simple, shoot down as many aliens as you can.

I made it to the point where I have player which can move and rotate, but I want the player to move in the angle, like 80s Asteroids (you set angle then press forward key and ship goes forward in that angle)

enter image description here

my movement now is simple:

up = y -= speed * delta time
down y += speed * delta time 
left x -= speed * delta time
right x += speed * delta time

my rotation is made like this:

ctx.save();
ctx.translate(this.x + this.w / 2, this.y + this.h / 2);
ctx.rotate(this.angle); 
Draw.Rect(ctx,this.w /2 * (-1),this.h / 2 * (-1),this.w,this.h,"red",1);//context,x,y,w,h,color,opacity
ctx.restore();

angle:

if(keys.e)this.angle += 0.1;
if(keys.q)this.angle -= 0.1;

javascript – refactoring code from syncronous to asyncronous flow

What I have

I have to take code that was build for web with react and adapt it to react native.. One of the biggest problems is, web storage(localStorage) works synchronously, while react-native storage implementations works asynchronously AsyncStorage. So all code that run/use web storage must now be wrapped inside an async/await or use promises in react-native implementation.

Code before refactoring – with synchronous storage

// get items from localstorage - synchronous wrapper implementation
export const getTokens = () => ({
  auth:
    localStorage.getItem(TOKEN_STORAGE_KEY.AUTH) ||
    sessionStorage.getItem(TOKEN_STORAGE_KEY.AUTH),
  refresh:
    localStorage.getItem(TOKEN_STORAGE_KEY.REFRESH) ||
    sessionStorage.getItem(TOKEN_STORAGE_KEY.REFRESH)
});

const refreshPromise = useRef<Promise<boolean>>();

const refreshToken = (): Promise<boolean> => {
    if (!!refreshPromise.current) {
      return refreshPromise.current;
    }

    return new Promise(resolve => {
      // getting items from storage synchronous
      const token = getTokens().refresh;

      // nested promise x_x
      return tokenRefresh({ variables: { token } }).then(refreshData => {
        if (!!refreshData.data.tokenRefresh?.token) {
          // this is other method that use localstorage inside promises, more problems x_x
          setAuthToken(refreshData.data.tokenRefresh.token, persistToken);
          return resolve(true);
        }

        return resolve(false);
      });
    });
  };

Problem

The problem is that I have encountered situations where storage is used inside a promise, and to adapt it to react-native I have to use asyncronous flow. i.e use async/await inside of a new Promise() constructor that is an anti-pattern.

the above brings a lot of problems, although using async/await inside the promise constructor is valid, firstly it makes the code less readable and secondly more difficult to debbug and check for errors. Another problem is synchronous implementation also nests promises which makes the code more complex to refactor.

Current code – with asynchronous storage

// get items from localstorage - asynchronous wrapper implementation
export const getTokens = async () => {
  const auth = await SecureStore.getItemAsync(TokenStorageKey.AUTH);
  const refresh = await SecureStore.getItemAsync(TokenStorageKey.REFRESH);

  return auth && refresh
    ? {
        auth,
        refresh,
      }
    : null;
};

const refreshPromise = useRef<Promise<boolean>>();

const refreshToken = (): Promise<boolean> => {
    if (refreshPromise.current) {
      return refreshPromise.current;
    }

    return new Promise(async resolve => {
      // getting items from storage asynchronous
      const tokens = await getTokens();
      const refresh = tokens?.refresh;

      // nested promise x_x
      return tokenRefresh({variables: {refresh}}).then(async refreshData => {
        if (refreshData.data?.tokenRefresh?.token) {
          // this is other method that use localstorage inside promises, more problems x_x
          await setAuthToken(refreshData.data.tokenRefresh.token);

          return resolve(true);
        }

        return resolve(false);
      });
    });
  };

What I want

according to this eslint rule:

If a Promise executor function is using await, this is usually a sign that it is not actually necessary to use the new Promise constructor, or the scope of the new Promise constructor can be reduced.*

I’m not clear how to achieve what the eslint rule mentions or make this code more escalable and easier to debug, Removing promises and avoiding nesting of asynchronous processes.

javascript – Pedir informação no Console pelo Node.js

Gostaria de saber como eu consigo fazer o console dizer algo do tipo “Qual seu nome?” aí o usuário escreve “Wheglybelson” aí depois o console retorna “Olá Wheglybelson!”, algm sabe como fazer? uso o atom e quero muito poder fazer essas coisas interativas pra mandar pros meus amigos, programo em javascript

javascript – ¿Como puedo recibir los datos que envio mediante fetch (JS) en un PHP?

Envié un objeto mediante fetch desde JavaScript, pero cunado intento obtener los datos en mi archivo PHP e insertarlos en mi base de datos MySQL, simplemente no se inserta ningún dato. Investigando encontré que los datos se podrían obtener así:

El archivo “be_connection.php” solo contiene la conexión a la base de datos

be_saveAvg.php


$promedio = json_decode(file_get_contents("php://input") , true);

$insertProm = mysqli_query($conexion, "INSERT INTO promedios(promedio) VALUES ('$promedio(0)')");

magento2 – Magento 2: Adding a Javascript library

I am trying to add an animation library called Sal, built on pure Javascript (Does not rely on jQuery). Maybe I am missing something, but I followed the instructions on adding via require-config, and I am getting a sal is not defined error.

I have also tried just adding the js file via default_head_blocks.xml

My require-config.js

var config = {
    paths: {
        'sal': 'js/sal'
    },
    deps: (
        "js/script",
        "js/main"
    )
};

My main.js

define(('sal'), function(){
  "use strict";
  sal();
  console.log(" ====== main.js is loaded====== ");
});