Edit a modal with option selected with onchange function

Im trying to open a edit modal, and load the results of this query.
My problems is the function “onchange” continue loading after the element was selected and changed it.

This is the function on the button to open the modal

const editModal = async (id, company, element) => {
 
  $("#companyEdit").val(insumo).select2().val();
  $("#elementEdit").val(element).select2().val();

  $("#edit").modal("show").attr("data-id", id);
 
};



This is the front

          .modal-body
                    .row(style="padding:15px;")
       
                        .col-md-12.col-12
                                .form-group
                                    label Company:
                                        select#companyEdit(onChange="selectElement()")
                                            option(disabled value=null) --Select-- 
                                            option(value=0) Sin asignar  
                                                each item in company
                                                    option(value=item.id)= item.name
                                     
                     
                        .col-md-12.col-12
                            .form-group
                                label Element:
                                .controls
                                    select#elementEdit(disabled)

This code works but delete the selected company.

const selectElement= async () => {


  let valueCompany= $("#companyEdit")
  let valueElement= = $('#elementEdit')
 
  const company_id= valueCompany.select2().val();
 

  $.ajax({
    method: "GET",
    url: `/admin-elements/${company_id}`,
    dataType: "json",

    success: function (data) {

      if (data.sucess == 200) {
        valueElement.empty();
        for (i = 0; i < data.result.length; i++) {
          valueElement.append('<option value="' + data.result[i].name+ '">' + data.result[i].name+ '</option>');
        }
        valueElement.attr("disabled", false);

      } else {
        valueElement.append(
          '<option value="">--</option>'
        );
        valueElement.attr("disabled", false);
      }
    },
    error: function (e) {
       ...
    },
  })

}

Thanks very much!!

I want can open a modal and see the select with the correct value with the possiblity of changed it with a query.

por favor ayudeme copn estos ejercicios en java netbeans en jframe

  1. Un negocio de perfumería efectúa descuentos en sus ventas según el importe de éstas, con la siguiente escala:
  • Si el importe es menor a $100 corresponde un descuento del 5%
  • Si el importe es de entre $100 (inclusive) y hasta $500 (inclusive) corresponde un
    descuento del 10%
  • Si el importe es mayor a $500 corresponde un descuento del 15%
    El dueño le solicitó a Ud., futuro programador, un programa donde se deba ingresar el importe original a pagar por el cliente y que luego se calcule e informe por pantalla el precio final con el descuento que corresponda ya aplicado.
  1. Hacer un programa para ingresar por teclado la nota obtenida por un alumno en una determinada materia y luego emitir el cartel aclaratorio que corresponda, de acuerdo a las siguientes condiciones:
  • “Sobresaliente”, si la nota fue 10.
  • “Distinguido”, si la nota fue 9 ó 8.
  • “Bueno”, si la nota fue 7 ó 6.
  • “Aprobado”, si la nota fue 5 ó 4.
  • “Insuficiente”, si la nota fue 3, 2 ó 1.
  • “Ausente”, si la nota fue 0.
  1. Hacer un programa para que dado un número igual o superior a 2 determine si es perfecto o no.
    Un número es perfecto cuando es igual a la suma de sus divisores positivos menores que él.
    Por ejemplo el 6, que es igual a la suma de 1+2+3.

Cannot set headers after they are sent to the client | Redirect causing issue?

I am redirecting a successful login to my admin page but once my app.get route with express is initiated it is throwing me the “Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client”.. Any ideas why?

app.post('/login', function(request, response) {
    // Capture the input fields
    let username = request.body.username;
    let password = request.body.password;
  console.log(username);
  console.log(password);
    // Ensure the input fields exists and are not empty
    if (username && password) {
        // Execute SQL query that'll select the account from the database based on the specified username and password
        con.query('SELECT * FROM something WHERE user = ? AND password = ?', [username, password], function(error, results, fields) {
            // If there is an issue with the query, output the error
            if (error) throw error;
            // If the account exists
            if (results.length > 0) {
                // Authenticate the user
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('Admin'); //redirect to app.get('/Admin')
            } else {
                response.send('Incorrect Username and/or Password!');
            }           
            response.end();
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});
//LOGIN SESSION //
 
app.get('/Admin', function (req, res) {
  if (req.session.loggedin) {
    activeEmails()
    .then((result) =>{
    var email = result;
    console.log(email);
    res.render('Admin', { //error is coming here!
      email : email
    });
  });
    } else {
        // Not logged in
        res.redirect('login');
    }
    res.end();
  });

TypeError: undefined is not an object (evaluating ‘process.version.slice’)

I’m trying to integrate the remove.bg API into a react native app. However, I’m not sure how to call a node js file from a react native button. Please let me know if I can clarify anything. Thanks for responces!

React Native JS Code containing remove.bg code:

global.Buffer = global.Buffer || require('buffer').Buffer
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const { newinputPath } = require('../Wardrobe');

const inputPath = newinputPath;
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
data: formData,
responseType: 'arraybuffer',
headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'kLJT2Gev5QbZe5epeexwrrKn',
},
encoding: null
})
.then((response) => {
if(response.status != 200) return console.error('Error:', response.status, response.statusText);
fs.writeFileSync("pics/no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});

Front-end code containing button:

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

let result;
export let newinputPath;

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);
  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
    newinputPath = result.assets[0].uri;
  };
   return (
     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
       <Button title="Pick an image from camera roll" onPress={pickImage} />
       {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
     </View>
   );
}

Optimistic Updates with React-Query (TRPC)

I am not sure how I would do optimistic updates with trpc? Is this “built-in” or do I have to use react-query’s useQuery hook?

So far, I am trying it like so, but it’s not working:

 const queryClient = useQueryClient();

    const updateWord = trpc.word.update.useMutation({
        onMutate: async newTodo => {
            // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
            await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] })

            // Snapshot the previous value
            const previousText = queryClient.getQueryData(['text', 'getOne'])

            // Optimistically update to the new value
            queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined)

            // Return a context object with the snapshotted value
            return { previousText }
        },
//...

Does this look like it should make sense? It’s updating the value, but not optimistically.

Discord.js Modal ValidationError

I’m attempting to make a bot but when I try to show the user a modal, I get the following error:

ValidationError: Expected the value to be a string or number

I’m not sure why this happens, but here is the code which seems to be causing it:


await interaction2.showModal(new ModalBuilder()
                        .setTitle('Create new field.')
                        .setCustomId('newtemplatefield')
                        .setComponents(...[
                            new ActionRowBuilder<TextInputBuilder>().addComponents(...[new TextInputBuilder().setLabel('Field Name').setCustomId('fieldname').setRequired(true)]),
                            new ActionRowBuilder<TextInputBuilder>().addComponents(...[new TextInputBuilder().setLabel('Field Description').setCustomId('fielddesc').setRequired(true)])
                        ]));

Chrome Extension suddenly not working, Errors page is blank

I’m new to Chrome Extensions and am trying to make a simple ‘Hello World’ extension – all it does is inject a .css file that makes ‘h1’ tags red.

This worked fine, until today when I resumed working on it and couldn’t get it to work again.

I noticed there is an Errors button against the Extension chrome://extensions/, but clicking it reveals nothing – a blank page. I removed and re-installed the extension, but the issue remains.

I am not getting any other errors and am stumped as to why this suddenly stopped working.

Would anyone know if I’ve done anything wrong?

My Manifest (V3) file:

{
    "name": "Hello World",
    "description": "Test",
    "version": "0.1.0",
    "manifest_version": 3,
    "icons": {
        "16": "/images/icon-16x16.png",
        "32": "/images/icon-32x32.png",
        "48": "/images/icon-48x48.png",
        "128": "/images/icon-128x128.png"
    },
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
            "16": "/images/icon-16x16.png",
            "32": "/images/icon-32x32.png",
            "48": "/images/icon-48x48.png",
            "128": "/images/icon-128x128.png"
        }
    },
    "options_page": "options.html",
    "permissions": [
        "storage",
        "activeTab",
        "scripting",
        "tabs"
    ]
}

My background.js file:

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete' && /^http/(tab.url)) {
        chrome.scripting.insertCSS({
            target: { tabId: tabId },
            files: ["./styles.css"]
        })
            .then(() => {
                console.log("INJECTED THE FOREGROUND STYLES.");
            })
            .catch(err => console.log(err));
    }
});

styles.css simply contains:

h1 {
    color: red !important;
}

My popup.html:

<!doctype html>
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <div><p>Hello World</p></div>
  </body>
</html>

And my options.html exists but is empty.

Would anyone be able to point me in the right direction?

How to maximize and minimize a div (no jquery only javascript)

hello I need to maximaze or minimize a div in my html page using only javascript no jquery i wanna be able to do like this http://jsfiddle.net/miqdad/Qy6Sj/1/

$("#button").click(function(){
    if($(this).html() == "-"){
        $(this).html("+");
    }
    else{
        $(this).html("-");
    }
    $("#box").slideToggle();
});

this is exactly how i want it to be but no jquery

but with no jquery only javascript, can someone please help me, I googled this everywhere and couldnt find the answer

Doesn’t redirect when pressing ok in the alert. Why?

The goal is that when the user presses ok in the alert window it will redirect them in a new page.But this doesnt seem to work when using if/else but does work on its own.How and why?

function CheckPassword(address,password,password2) {
  if ((password =="") || (password2 =="") || (address == "")) {
    alert("Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά")
  }
  else {
    alert('message');
    window.location = 'new page.html';
  }   
}

function ClickMe () {
  CheckPassword( document.getElementById('password2').value 
               , document.getElementById('password').value
               , document.getElementById('address').value )
}

document.getElementById('btn').addEventListener("click",function(){ClickMe()} );

How would I go about making elements underneath a div visible?

I have beent trying to make a “hiddent text” website of sorts.

I have managed to code a circular div that follows my mouse cursor and inverts every text underneath it using background-filter in CSS and Javascript:

let circle = document.getElementById('circle');const onMouseMove = (e) =>{
    circle.style.left = e.pageX + 'px';
    circle.style.top = e.pageY + 'px';
  }
  
  document.addEventListener('mousemove', onMouseMove);

The CSS for the #circle element is:

#circle {

    position:absolute;
    transform:translate(-50%,-50%);
    height:80px;
    width:80px;
    border-radius:50%;
    box-shadow: 0px 0px 40px 10px white;
    pointer-events: none;
    backdrop-filter: invert(100%); 
    z-index: 100;
}

Now, I have tried setting the text’s opacity to 5% and then setting backdrop-filter: opacity(100%) but that didn’t work, unfortunately. How should I go about achieving this? I am open to any and all libraries and willing to follow any tutorial. Accesibility is not an issue at the moment as this is just an experiment for myself.

assigning a value to one array index assigns it to all of them?

var measureinc = 16;
var initnotedefining = new Array(
    9
    2
    5
    10
    3
    6
    7
    0
);
var score = new Array(
);
var currentmeasure = 1;
var currentnote = 1;
// ^ (not quite how these are defined in the program, but for the sake of reproducing it easier...)
for(i1 = 0; i1 < measureinc; i1++){
// searches initnotedefining for every possible note position.
// every iteration increases the position value it's looking for
    for(i2 = 1; i2<initnotedefining.length; i2++){
    // searches every entry in initnotedefining for the current
    // position value the bigger for loop wants
        if(initnotedefining[i2]===i1) {
            score[currentmeasure[currentnote[0]]] = initnotedefining[i2];
            console.log("new note assigned to the measure's array. the position value is " + score[currentmeasure[currentnote[0]]]);
            currentnote += 1;
        };
    }
}

this for loop is supposed to form the score[currentmeasure] array. the array structure is:

score (array)

  • measures (arrays)
    • notes (arrays)
      • aspects of those notes (in this case, the only one of these i’m editting is 0, the position value)

initnotedefining is an array that i defined earlier, (its structure is normal, there’s no nested arrays) and this is supposed to put the values in it into score[currentmeasure], with them being ordered by value, and those values being put into the 0 area of every note’s array.

instead, when i try to retrieve all the score[currentmeasure[i[0]]] values, all of them are exactly the same as whatever the last note defined was.

using console.log, it seems that every instance of score[currentmeasure[currentnote[0]]] = initnotedefining[i2]; assigns the initnotedefining[i2] value to every possible note. even ones that aren’t defined yet, and ones that shouldn’t exist, like note numbers that are ridiculously high, or indexes that should be invalid, like negatives, decimals, and fractions.

if(currentnote===3) {
    console.log(score[currentmeasure[1[0]]] + " " + score[currentmeasure[2[0]]] + " " + score[currentmeasure[3[0]]]);
};
// i tried to put this within that if statement, and it gave me the third note's value three times.

the thing is, that console.log command shows that the reordering is working fine. i can see in the console that all those notes are being reordered perfectly, and their values vary as much as they should. but when i try to retrieve those values, they’re all the same, whether i do that after this set of for loops or within it.

i tried to set score[currentmeasure].length as initnotedefining.length before these for loops, but when i tried to run it firefox started slowing down and asked me to stop the script. the same thing happens when i set score[currentmeasure].length as 5, so the problem seems to be defining score[currentmeasure].length at all… even though MDN says there shouldn’t be a problem with doing that. (that said, i’m not sure if defining the length would even fix this.)

i have no idea what could cause this. any assistance would be greatly appreciated.

Run MathJax at specific point or re-run it somewhere in code

Let me simplify the script:

  1. Gets input from user

  2. Calculates stuff

  3. Adds calculated stuff to HTML with MathJax

The problem is, that MathJax runs at the beginning, when the stuff is not calculated yet. It shows ‘undefined’ in equations. Later, when it’s calculated, the equations looks something like this $ l_D = 3m $

Is there any way to run MathJax at specific point? Or to re-run it after that stuff is calculated?