Why is my function executing when clicking on an input element and not a button?

Currently making an expense tracker. One of my functions adds an expense to a div titled history. This is the function:

function addExpense()
{
        clothingID={'id':Date.now(),'clothingType':clothingType.value, 'brand': brand.value, 'amnt':amnt.value, };
        clothingArray.push(clothingID);
        count1++;
        showTotalBalance();
        showDifference();
        expenseHistory();
        clothingType.value='';
        amnt.value='';
        brand.value = '';
        setItemInStorage();       
}

Once the user inputs an expense, it should look something like this (please excuse bad design):

Example output

Originally, this was done through the following code:

<form id = "clothingExpenses" class = 'display'>
            <div  style = 'text-align:center;' class="row">
               <div style = 'text-align:center;' class="six columns">
               <label style = ' padding-bottom: 1pt; text-align:center;' for="exampleEmailInput">Clothing type</label>
            <input  id = 'type' astyle = "width: 50%;" type="email" placeholder="Enter the clothing type" id="exampleEmailInput">
              </div>
            </div>
                  <div>
           <label style = ' padding-bottom: 1pt;' for="exampleEmailInput">Amount</label>
            <input id="amnt" style = "width: 24%;" type="number" placeholder="Enter number" id="exampleEmailInput">
                      </div>
                      <div>
             <label style = 'padding-bottom: 1pt;' for="exampleEmailInput">Clothing brand</label>
           <input id="brand" style = "width: 24%;" type="text" placeholder="Enter the clothing brand" id="exampleEmailInput">
                      </div>
                
                
        <button type = 'button' class="button-primary" onclick="addExpense()">Add expense</button>
         <button type = 'button' class="button-primary" onclick="closeExpenseForm()">Close form</button>

 </form>

The button with the onclick action of addExpense() would execute this function fine. However, I needed to alter the code in order to have an action for the form, which would send user input to a Google Sheet. I therefore had to move the onclick action up in my form element.

Here is the updated form:

      <form method="POST" action = "https://script.google.com/macros/s/AKfycbyoRaf291Z8ud57I70QwyHv7alefLhul3WLKpFCc3K0FjlEIWHzsoN8ZmC2jKSEg/exec" onclick = "addExpense()" id = "clothingExpenses" class = 'display'>
                    <div class="row">
                      <div  class="six columns">
                        <label>Clothing type</label>
                        <input  name = "Type" id = 'type' style = "width: 50%;" type="text" placeholder="Enter the clothing type" id="exampleEmailInput">
                      </div>
                    </div>
                    <div>
                    <label>Amount</label>
            <input name = "Amount" id="amnt" style = "width: 24%;" type="number" placeholder="Enter number" id="exampleEmailInput">
             </div>
             <div>
                    <label style = 'padding-bottom: 1pt;' for="exampleEmailInput">Clothing brand</label>
             <input name = "Brand" id="brand" style = "width: 24%;" type="text" placeholder="Enter the clothing brand" id="exampleEmailInput">
                      </div>
                  
       <button type = 'submit' class="button-primary">Add expense</button>
       <button type = 'submit' class="button-primary" onclick="closeExpenseForm()">Close form</button>

</form>

After moving the onclick action further up, the addExpense() function now runs when simply clicking on an input element as such:

Input element

And provides the following output:

Wrong output

Any ideas on why this is occurring and how I can fix this?

svg element wont scale accordingly

New react developer here, i have been trying to solve this svg problem for a while,

When i try to resize image (in my code image is in canvas), by pulling to left and right, image does what it should do, but i have svg elements on the image and that wont resize, my point is when i resize image then svg lines and circle should also resize because those are on image

here is small part of image

enter image description here

as you can see i have lines connected to circle(those are svg) and behind it is that image, so when i resize using ‘allotment’ image will resize but svg wont.

here is example code those images are in canvas in my version:
https://codesandbox.io/s/amazing-http-6bdt88?file=/src/App.js

code:

const _zoomConfig = () => {
    const z = d3Select(`#graph-id-graph-wrapper`)
      .call(d3Zoom() as any)
      .on('wheel.zoom', null)
      .on('dblclick.zoom', null)
      .on('mousedown.zoom', null)
      .on('touchstart.zoom', null)
      .on('touchmove.zoom', null)
      .on('touchend.zoom', null);
  };
  
  
  useEffect(() => {
    _zoomConfig();
  });
#graph-id-graph-wrapper {
  /* margin-left: -100%; */
  width: 100%;
  height: 100%;
}

i tried this set height and width to 100% and that didnt work, should i be using viewBox here?

English is not my mother language so there could be mistakes

useEffect(() => {
    const k = Array.from(document.getElementsByTagName('svg')).map(
      (elem) => elem,
    );

   
    k.map((elem) => {
      if (elem.getAttribute('name') === 'svg-container-graph-id') {
        elem.setAttribute('height', '100%');
        elem.setAttribute('width', '100%');
      }
    });
  });

console:

enter image description here

NodeJS: UnhandledPromiseRejection when promise is rejected before await

I have two promises without catch blocks in the beginning and I’m doing await on both of them later with catch blocks. Second promise rejects before first promise resolves. So, while I’m still awaiting on the first promise, second promise is rejected and since I have not attached the catch yet, it crashes the server with UnhandledPromiseRejection.

Is there a way to make p2’s reject propagate to await p2, like it does in case when p2 resolves?

PS: I cannot attach the catch in the beginning itself.

Adding the code below for reference. In stackoverflow it works fine for some reason, but when run from local, the server crashes.

async function main() {
  console.log("starting");
  let p1 = new Promise((resolve, reject) => {
    console.log('p1 sleeping');
    setTimeout(function() {
      console.log('p1 awake');
      resolve('p1 resolved');
    }, 5000);
  });

  let p2 = new Promise((resolve, reject) => {
    console.log('p2 sleeping');
    setTimeout(function() {
      console.log('p2 awake');
      reject('p2 rejected');  //IMPORTANT
    }, 1000);
  });

  //Below line takes 5 seconds to execute.
  //But p2 throws error after 1 second because no .catch() is attached to it yet.
  let out1 = await p1.catch(e => {
    console.log('p1 errored', e)
  });
  console.log('p1 output', out1);

  let out2 = await p2.catch(e => {
    console.log('p2 errored', e)
  });
  console.log('p2 output', out2);
}

main().then(() => {
  console.log('stopped')
});

React audio player – custom css

I have nextjs project and I need react-h5-audio-player
. I need to customize the css of react audio player. I tried to import css and to overwrite its custom css but my new css don’t work. How can I change the css of this audio player .

Circular Update on time based webpage

I’m trying to set up two pages to swap between each other based on the time of the day. So between 8 am to 10 pm it goes to BBC one page, if not it goes to the BBC news page. I came up with the below, but the page keeps getting stuck on refreshing again and again at some point it stops and go, but I would like to make it more straight forward eliminating this circulation. I don’t know what is wrong, to be honest, it seemed to be working fine but every time it triggers the refresh the page takes a lot of time dealing with something loading again and again.

<!DOCTYPE html>
<html>

<script>
var hours = new Date().getHours();
if(hours >= 8 && hours >= 10){
  window.location.href = "file://S:/Astraia/Data/Staff TV/BBCone.html";
}else{
  window.location.href = "file://S:/Astraia/Data/Staff TV/BBCnews.html";
}
</script>

<head>
<meta charset=utf-8 />
<title>:: Soft Services | Now ::</title>
  <style type="text/css">
body {
    background-color: #000000;
  overflow-y: hidden; /* Hide vertical scrollbar */
  overflow-x: hidden; /* Hide horizontal scrollbar */
}
</style>
<meta http-equiv="refresh" content="3500">

  <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
  <script src="https://unpkg.com/video.js/dist/video.js"></script>
  <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
   
</head>
<body>
  <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto" autoplay="autoplay" data-setup='{}'>
  <source src="https://bbc.iplayer.com" type="application/x-mpegURL">
</video>
<script>
var player = videojs('my_video_1');
player.play();
</script>

      
</body>
</html>

This

Filter the value from the array

Orginal array contains the arrays of the view in n level (nested view). That array is used to generate the dynamic sidemenu.

orginal array

const routes = [
      {
        collapse: true,
        name: "Student Information",
        state: "studentInformationCollapse",
        views: [
          {
            collapse: true,
            name: "Student ID Set up Values",
            state: "studentIdSetCollapse",
            views: [
              {
                path: "/gender",
                name: "Gender",
               
                layout: "/admin",
              },
              {
                path: "/phonetype",
                name: "Phone Type",
                
                layout: "/admin",
              },
              {
                path: "/addresstype",
                name: "Address type",
                
                layout: "/admin",
              },
              {
                path: "/emailType",
                name: "Email Type",
                
                layout: "/admin",
              },
              {
                path: "/academicCareer",
                name: "Academic Career",
                
                layout: "/admin",
              },
             {
            collapse: true,
            name: "Student ID Set up Values",
            state: "studentIdSetCollapse",
            views: [
              {
                path: "/parentOccupation",
                name: "Parent Occupation",
                
                layout: "/admin",
              },
              {
                path: "/academicCareer",
                name: "Academic Career",
                
                layout: "/admin",
              },
            ],
          },
            ],
          },
        ],
      },
     
];

Filter by using this array that contains the name of views name

[ "Gender","Parent Occupation"]

After Filter array will look like this.

const routes = [
      {
        collapse: true,
        name: "Student Information",
        state: "studentInformationCollapse",
        views: [
          {
            collapse: true,
            name: "Student ID Set up Values",
            state: "studentIdSetCollapse",
            views: [
              {
                path: "/gender",
                name: "Gender",
                component: Gender,
                layout: "/admin",
              },
         
             {
            collapse: true,
            name: "Student ID Set up Values",
            state: "studentIdSetCollapse",
            views: [
              {
                path: "/parentOccupation",
                name: "Parent Occupation",
                component: ParentOccupation,
                layout: "/admin",
              },
            ],
          },
            ],
          },
        ],
      },  
];

Thanks in advance. I don’t have so much time please help me !

useState weird update

I have this function that get some data and put in a array, and, in the end, change de value of the test useState to the content of that array

const [teste, setTeste] = useState('DefaultValue');
const fetchTeses = () => {
      const textTeses = [];
      fetch('http://localhost:8000/teses')
      .then(res => {
          if(!res.ok){
              throw Error('Could not fetch the data for that resource')
          }
          return res.json()
      })
      .then((data) => {
        items.forEach((element, index) => {
          tesesEscolhidas.forEach((teseEscolhida) => {
            if(element.indexOf(teseEscolhida)!=-1){
              textTeses.push(data[index]['Content']);
            }
          })
        })
      }).then((data) => {
        setTeste(textTeses)
      })
    }

This function is called by clicking on a button:

<Button color="secondary" size="large" variant="contained" onClick={fetchTeses}>Resetar</Button>

But I call the test useState in another function, which is called by clicking in another button:

<Button color="primary" size="large" variant="contained" onClick={generateFromUrl}>Criar arquivo docx</Button>

The second function:

    const generateFromUrl = async() => {
      const blob = await fetch(
        "https://raw.githubusercontent.com/dolanmiu/docx/master/demo/images/cat.jpg"
      ).then(r => r.blob());
  
      const doc = new Document({
        sections: [
          {
            children: [
              new Paragraph(teste[0])
            ]
          }
        ]
      });
  
      Packer.toBlob(doc).then(blob => {
        console.log(blob);
        saveAs(blob, nameFile+".docx");
        console.log("Document created successfully");
      });
    }

But the weird part is that when I call the test useState in the second function he pass the DefaultValue, even though I have already executed the first function and already assigned the new value to the test useState. (I notice that if I execute the first function more than once, the new value is finally assigned)

However, when I create an element with test useState value and do the exaclty same thing, the value passed in the second function is the new value assigned in the first function, which is what i want to happen.

Example:

<TextField id="nameTest" label="Teste" variant="outlined" color="primary" fullWidth helperText="Teste" value={teste ? teste : ''} />

Why is this happening and how to avoid this?

I know this has to do with the render thing, but I really can’t figured out how to made this works.

Testing for 2 arrays that have duplicates. cant get the last test to come back pass

Attempting to get the below code to pass the test at the bottom. I believe my issue is inside the registerStudent()

I am supposed to do the following:

In this task, you will add the method registerStudent() to the Bootcamp class.
This method should have a single parameter called studentToRegister. This parameter will take an object created from the Student class as its argument.
In the method body, if the studentToRegister argument does not possess either a name and a email property, console.log() the string ‘Invalid name or email’ then return the Boolean value of false.
Otherwise, iterate through the this.students array to check for if any of the students in that array have the same email as the studentToRegister. Compare the email of each student in the this.students array to the email of the studentToRegister.
There are multiple potential ways to check this, including the for ... of loop method you learned last week.
If you want to take on a challenge, you could try researching how to use the array method called find(), which we have not yet covered.
In the case that a matching email is found, console.log() a string that says that email is already registered, then return false.
Otherwise:
Use the array method push() to add the studentToRegister object to the this.students array.
console.log() a message indicating success, using the studentToRegister‘s name and the bootcamp‘s name in the message.
return the Boolean value of true.

class Student {
    constructor(name, email) {
        this.name = name;
        this.email = email;
    }
}

class Bootcamp {
    constructor(name, level, students = []) {
        this.name = name;
        this.level = level;
        this.students = students;
    }
    registerStudent(studentToRegister = Student) {
        function studentToRegister(Student); {
            for (let i = 0; i < this.students; i++) {
                for (let j = 0; j < studentToRegister.length; j++) {
                    if (this.students[i] == studentToRegister[j]) {
                        console.log('That email is already registered')
                        return false;
                    }
                    else {
                        this.students.push(studentToRegister); {
                            console.log(`${studentToRegister} is now registered`)
                            return true;
                        }
                    }
                }
            }
        }
    };
}
testStudent = new Student('Bugs Bunny', '[email protected]');
console.log(testStudent);
if (testStudent.name === 'Bugs Bunny' && testStudent.email === '[email protected]') {
    console.log('TASK 1: PASS');
};



reactBootcamp = new Bootcamp("React", "Advanced");
console.log(reactBootcamp);
if (reactBootcamp.name === 'React' && reactBootcamp.level === 'Advanced'
    && Array.isArray(reactBootcamp.students) && reactBootcamp.students.length === 0) {
    console.log('TASK 2: PASS');
}

const runTest = (bootcamp, student) => {
    const attemptOne = bootcamp.registerStudent(student);
    const attemptTwo = bootcamp.registerStudent(student);
    const attemptThree = bootcamp.registerStudent(new Student("Babs Bunny"));
    if ( attemptOne && !attemptTwo && !attemptThree) {
        console.log("TASK 3: PASS");
    }
};

runTest(reactBootcamp, testStudent);

How to change styles/remove certain elements when moving elements from one list to another using sortable?

This is the case. I have List 1 (id=favoriteList) and List 2 (id=otherList).

The code for list one is this:

<div class="generic_feature_list" data-role="content" data-theme="c">
   <ul data-role="listview" data-inset="true" data-theme="d" id="favoriteList">
      <li data-role="list-divider">
         <div class="row">
            <div class="col-md-6">
               <span>Holidays</span>
            </div>
            <div class="col-md-6">
               €2000
            </div>
         </div>
      </li>
   </ul>
</div>

The code for list 2:

<div data-role="content" data-theme="c">
   <ul style="list-style-type: none;" data-role="listview" data-inset="true" data-theme="d" id="otherList">
      <li data-role="list-divider">
         <div class="row">
            <div class="col-xl-6 col-lg-6">
               <div class="card l-bg-blue-dark">
                  <div class="card-statistic-3 p-4">
                     <div class="card-icon card-icon-large"><i class="fas fa-laptop"></i></div>
                     <div class="mb-4">
                        <h5 class="card-title mb-0">Laptop</h5>
                     </div>
                     <div class="row align-items-center mb-2 d-flex">
                        <div class="col-8">
                           <h2 class="d-flex align-items-center mb-0">
                              €1500
                           </h2>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </li>
   </ul>
</div>

and my js and refs:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://raw.githack.com/SortableJS/Sortable/master/Sortable.js"></script>
<script>
let favoriteList = document.getElementById('favoriteList');
let otherList = document.getElementById('otherList');

let favorite_list = Sortable.create(favoriteList, {
    animation: 150,
    group: 'shared',
    ghostClass: 'sortable-ghost',
});

let other_list = Sortable.create(otherList, {
    animation: 150,
    group: 'shared',
    ghostClass: 'sortable-ghost',
    sort: false
});

$(function(){
    var removeIntent = false;
    $('#otherList').sortable({
        over: function () {
            removeIntent = false;
        },
        out: function () {
            removeIntent = true;
        },
        beforeStop: function (event, ui) {
            if(removeIntent == true){
                ui.item.remove();   
            }
        }
    });
});
</script>

I would like to transform the elements from list 2 like elements from list 1 so I suppose I would need to remove certains divs and change some styles.

I’ve followed these instructions with no luck:
How to remove the text of sortable area when item is dropped on it?
Sortable element stay after remove()
How to remove an item that is pulled away from it’s list?
How to change sortable element’s style while dragging?
Remove item after successful JQuery Sortable action
jQueryUI Sortable – Remove a li from the sortable list

Could somebody please help me?

duplicated of it mini-card-trigger

hi there stackoverflow friend, i am trying to run my code in my .net core project at the menu section, problem is i only can load the card section either in mobile or desktop mode, but i want when move to mobile mode have the card displayed. here is the code for html and javascript, is there an if statement for example i say if you are mobile open it and desktop load this, i guess it is because it is duplicated, thanks and i am new to stackoverflow, apologies if i am bit of unclear.

                                                <div class="header-cart-icon">
                                                    <a href="#" id="minicart-trigger">
                                                        <i class="ion-bag"></i>
                                                        <span class="counter" id="cart_items_count">0</span>
                                                    </a>
                                                    <div class="mini-cart" id="mini-cart">
                                                        <div class="cart-items-wrapper ps-scroll" id="cart_items_wrapper">

                                                        </div>
                                                        <div class="cart-buttons">
                                                            <a asp-page="/Cart">view card</a>
                                                        </div>
                                                    </div>
                                                </div>


 $('#minicart-trigger').on('click', function(e){
        e.preventDefault();
        $(this).siblings('.mini-cart').toggleClass('active');
        $('#settings-menu-wrapper').removeClass('active');
        $('body').addClass('active-overlay');
    });

    $('#header-settings-trigger').on('click', function(e){
        e.preventDefault();
        $(this).siblings('.settings-menu-wrapper').toggleClass('active');
        $('#mini-cart').removeClass('active');
        $('body').addClass('active-overlay');
    });

    $('#currency-trigger').on('click', function(e){
        e.preventDefault();
        $(this).siblings('#currency-menu').toggleClass('active');
        $('body').addClass('active-overlay');
    });

    $('#language-trigger').on('click', function(e){
        e.preventDefault();
        $(this).siblings('#language-menu').toggleClass('active');
        $('body').addClass('active-overlay');
    });

    /*Minicart Close When Click Outside Minicart*/

    $('body').on('click', function(e){
        var $target = e.target;
        if (!$($target).is('.header-cart-icon, .header-settings-icon, #currency-trigger, #language-trigger') && !$($target).parents().is('.header-cart-icon, .header-settings-icon, #currency-trigger') && $('body').hasClass('active-overlay')) {
           $('.mini-cart, .settings-menu-wrapper, #currency-menu, #language-menu').removeClass('active');
           $('body').removeClass('active-overlay');
        }
    });

function addToCart(id, name, price, picture) {
    let products = $.cookie(cookieName);
    if (products === undefined) {
        products = [];
    } else {
        products = JSON.parse(products);
    }

    const count = $("#productCount").val();
    const currentProduct = products.find(x => x.id === id);
    if (currentProduct !== undefined) {
        products.find(x => x.id === id).count = parseInt(currentProduct.count) + parseInt(count);
    } else {
        const product = {
            id,
            name,
            unitPrice: price,
            picture,
            count
        }

        products.push(product);
    }

    $.cookie(cookieName, JSON.stringify(products), { expires: 2, path: "/" });
    updateCart();
}

How to find smallest and biggest value from list of elements, in most efficient way?

I have a two sets of elements, one holds list of numbers and second of names.
something like this.

A: 4,
B: 3,
C: 2,
A: 5,
C: 3,

And my task is to find elements with smallest value and highest value.
I know that i could create array of objects and sort it with map [{A: 4},{C:2}....]
But i was wondering is there any efficient ways of doing it.
Instead of creating a have object, and use three loops.
Would it be possible to replace it with something more efficient.
Like set or something where i could just call set.getItemWithMinValue, set.getItemWithMaxValue
and return would be : C:2, A:5

Sorry for silly quesition, i am still learning.

how to use bootstrap 5 popover in reactjs components

I have seen many videos where people activate bootstrap 5 popovers using

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})

in just HTML file. I haven’t found any blogs or videos where people activate the popover in reactjs files. Please suggest me some examples..I am really stuck in my given task because of this popover. please someone suggest me a good example.

How can I update the ID on the select?

I want that when a user selects an option it updates the ID for “Treat” so I can use it in code for some other things. When I try it uses the first option as the id not the other ones.

I don’t care any type of code works just needs to be useable in a website environment!

<select style="font-size:20px;"  id="Treat" class="textbox" form-control form-group > 
   <option style="font-size:25px;" selected>Pick Treat...</option>  
   <option style="font-size:25px;" value="Brownie">Brownie</option>
   <option style="font-size:25px;" value="Chocolate Chip Cookie">Chocolate Chip Cookie</option>