Buttons get deselected due to a click event anywhere on the webpage

I have made a Bill Splitter which basically calculates the tip and the total amount each person has to pay on a bill. It has multiple button to select the tip percentage. These buttons are deselected when the user clicks anywhere on the webpage. I want that the buttons be deselected only when the user clicks on any other button. Please correct my code.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <title>Tip Calculator App</title>
  <!--Font Awesome Links-->
  <script src="https://kit.fontawesome.com/fd6cc398e6.js" crossorigin="anonymous"></script>
  <!--Bootstrap Links-->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <!--CSS Links-->
  <link rel="stylesheet" href="styles.css">
  <!--Google Fonts-->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,700;1,700&display=swap" rel="stylesheet">
</head>
<body>

  <div class="top-heading">
    <h4 class="line1">SPLI</h4>
    <h4 class="line2">TTER</h4>
  </div>

  <main>
    <div class="calculator">
      
      <div class="left-box">
        <h6>Bill</h6>
        <span class="text-addon"><i class="fa-solid fa-dollar-sign"></i></span>
        <input type="text" class="left-input" id="amount">
        <h6>Select Tip %</h6>
        <button type="button" class="btn btn-primary tip">5%</button>
        <button type="button" class="btn btn-primary tip">10%</button>
        <button type="button" class="btn btn-primary tip">15%</button>
        <button type="button" class="btn btn-primary tip">25%</button>
        <button type="button" class="btn btn-primary tip">50%</button>
        <input type="text" class="left-input" id="custom" placeholder="Custom">
        <h6>Number of People</h6>
        <span class="people-addon"><i class="fa-solid fa-person"></i></span>
        <input type="text" class="left-input" id="people">
      </div>

      <div class="right-box">
        <h5>Tip Amount / person</h5>
        <input type="text" id="tipPerPerson" class="right-input" readonly placeholder="$0.00"><br><br><br>
        <h5>Total / person</h5>
        <input type="text" id="totalPerPerson" class="right-input" style="margin-left: 40px;" readonly placeholder="$0.00"><br><br><br>
        <button type="button" class="btn btn-primary btn-lg" id="reset">Reset</button>
      </div>

    </div>
  </main>
  <script src="./index.js"></script>
</body>
</html>

CSS:

body {
    background-color: hsl(185, 41%, 84%);
    font-family: "Space Mono";
}

h4 {
    color: hsl(183, 100%, 15%);
    letter-spacing: 15px;
    margin: 5% 50% 0% 45%;
}

h5 {
    font-size: small;
    color: #fff;
    display: inline-block;
}

h6 {
    margin: 3%;
    color: hsl(185, 22%, 45%);
}

.line2 {
    margin-top: 0%;
}

.calculator {
    display: flex;
    margin: 4% 15% 0% 20%;
    background-color: #fff;
    border-radius: 2.5%;
    z-index: 1;
    width: 60%;
    padding: 0.9%;
}

.left-box {
    float: left;
    background-color: #fff;
    width: 50%;
    padding: 2%;
    box-sizing: border-box;
}

.left-input {
    background-color: hsl(189, 41%, 97%);
    border: none;
    margin-bottom: 5px;
    text-align: right;
    color: hsl(183, 100%, 15%);
    width: 80%;
}

.left-input:focus {
    outline: none !important;
    border:1px solid aquamarine;
    box-shadow: 0 0 10px #719ECE;
}

#custom {
    display: inline-block;
    background-color: hsl(189, 41%, 97%);
    color: hsl(183, 100%, 15%);
    width: 25%;
    height: 11%;
    text-align: center;
    border-radius: 5%;
    cursor: pointer;
}

.btn {
    width: 80px;
    margin-right: 20px;
    margin-bottom: 10px;
    background-color: hsl(183, 100%, 15%);
    border: none;
}

.btn:focus {
    background-color: hsl(166, 61%, 39%);
}

.custom:focus {
    background-color: hsl(161, 28%, 62%);
    color: #fff;
}

.right-box {
    float: right;
    width: 50%;
    box-sizing: border-box;
    background-color: hsl(183, 100%, 15%);
    padding: 2.5%;
    border-radius: 5%;
}

.right-input {
    width: 50%;
    background-color: hsl(183, 100%, 15%);
    border: none;
    outline: none;
    color: hsl(161, 42%, 58%);
    text-align: right;
    height: 30px;
    font-size: xx-large;
}

.btn-lg {
    background-color: hsl(161, 42%, 58%);
    width: 100%;
    margin-top: 100px;
}

@media only screen and (max-width: 600px) {
    h4 {
        margin: 5% 30% 5% 40%;
    }

    .calculator {
        display: inline-block;
        width: 100%;
        margin-left: 0%;
    }

    .left-box {
        display: inline-block;
        width: 100%;
        margin-left: 0%;
    }

    .right-box {
        display: inline-block;
        width: 100%;
        margin-left: 0%;
    }
}

JS:

let bill_amount = document.getElementById("amount");
let humans = document.getElementById("people");
let tip_buttons = Array.from(document.getElementsByClassName("tip"));
let reset_button = document.getElementById("reset");
let custom_tip_button = document.getElementById("custom");
let tip_percentage, tip_person, total_bill_person;
let bill_amountFilled = false;
let humansFilled = false;
let buttonClicked = false;

tip_buttons.forEach(function (button) {
  button.addEventListener("click", function (event) {
    tip_percentage = parseFloat(button.innerHTML);
    buttonClicked = true;
    calculateTip();
});
});

custom_tip_button.addEventListener("input", function(event) {
    tip_percentage = parseFloat(event.target.value);
    buttonClicked = true;
    calculateTip();
});

function calculateTip() {
  if (bill_amountFilled && humansFilled && buttonClicked) {
    tip_person = (parseFloat(bill_amount.value) * (0.01 * parseFloat(tip_percentage))) / parseFloat(humans.value);
    total_bill_person = parseFloat(bill_amount.value) / parseFloat(humans.value) + tip_person;
    document.getElementById("tipPerPerson").value = tip_person.toFixed(2);
    document.getElementById("totalPerPerson").value = total_bill_person.toFixed(2);
  }
}

bill_amount.addEventListener("input", function (event) {
  if (bill_amount.value.trim() !== "") {
    bill_amountFilled = true;
    calculateTip();
  } else {
    bill_amountFilled = false;
  }
});

humans.addEventListener("input", function (event) {
  if (humans.value.trim() !== "") {
    humansFilled = true;
    calculateTip();
  } else {
    humansFilled = false;
  }
});

reset_button.addEventListener("click", function(){
    location.reload();
});
document.addEventListener("click", function(event) {
    event.preventDefault();
  });

I tried using the contains function to check whether any click event is inside the tip buttons or not, but I couldn’t do it successfully. Being a beginner to JavaScript I am not able to think of any other way to solve this issue.

How to send Boolean value in params?

     this.apiService.sendRequest(requests.getAllInternalStatuses+ '?isInternal=' +isInternal, 'get')
     .subscribe((res: any) => {
      this.tableData = res.data;
      console.log("Table Data",this.tableData);
     })

I’m using this api to send isInternal=true, but it gives me an error saying that isInternal must be a boolean value. Can anyone help me with this, how to send boolean value in params?

problem with creating a connection between an event calendar and SQL database filled with events

I really need help with my project. I did an event calendar using html, CSS, and JavaScript
my problem is how can i make a connection such as a node to a database filled with certain events to appear on the calendar on a certain date??
also, how to insert an event into the database in a different table?
i tried to use “connection string” but it did not work.
I’m using visual studio 2022.

Is setting a props’ data as a state’s value is call by reference? [duplicate]

I’m a little bit confused how the call by reference/value would work between React component.

I have a component which pass its data to a Table component, in which the Table component will store the passed data for sorting purpose.

function User(){
  const [userList, setUserList] = useState([])
  //fetch and update userList
   ...

  function renderBody(){
     return userList.map(user=> 
        <tr>
           <td>{user.name}</td>
        </tr>
    )
  }

  return <Table data={userList} renderBody={renderBody} />
}

function Table({data, renderBody}){
  const [cache, setCache] = useState([])

  useEffect(()=>{
    if(data){
        setCache(data)
    }
  },[data])

  function sortOrder(){
    //using cache data and perform sorting
    const temp = cache.sort((x, y) => String(x[id]).localeCompare(y[id], 'en', { numeric: true }))
    setCache(temp)
  }
  
  return <table>{renderbody()}</table>

In my case, I forget to use the cache data to render the body of table. However, the sorting function still work! Even I only sorting the cache data, the original data (here the userList) is also sorted.

My Questions are:

  1. Is it work because of something like call by reference?

  2. Should I keep using this way to sort and render the data? Or it is better to let the render function use the cache data instead?

React Query: Not catching 404

When running the following code (Repo) my page fails to render entirely. There is no catch going on. The useQuery hook doesn’t show an error as per this sort of video.

export const fetchCars = async () => {
  const resp = await fetch(CARS_ENDPOINT.slice(0, -3)); // intentional 404 creation
  console.log(resp);
  if (!resp.ok) throw new Error("Failed to fetch");
  return await resp.json();
};
export const useCars = ({ onSuccess, onError } = {}) =>
  useQuery({
    queryKey: [STORAGE_KEY],
    queryFn: fetchCars,
    onSuccess,
    onError,
  });
const CarsListPage = () => {

  const deleteMutation = useDelete();

  const deleteHandler = (id) => {
    deleteMutation.mutate(id);
  };

  const { data, isLoading, error, isError, isFetching } = useCars();

  let component = null;

  if (isLoading || isFetching) {
    component = <CircularProgress />;
  } else if (isError) {
    component = <p>Error: {JSON.stringify(error)}</p>;
  } else {
    component = <CarsList cars={data} deleteHandler={deleteHandler} />;
  }

  return (
    <>
      <Typography variant="h3" component="h2">
        Cars
      </Typography>
      {component}
    </>
  );
};

export default CarsListPage;

I’m just at a loss as to why it causes such a catastrophic break?! Can anyone help?

Thanks

How do I compare using the JavaScript typeof()

I have an function to sum any numbers of args. I tried the following code:

function sumOfArrayItems(...args){
var sum = 0;
for (const item of args)
{
    var num = 1;
    if((typeof(item)) == (typeof(num))){
        sum += item;
    }
}
return sum;

It gives us the desired output. The only this I didn’t get is: when I tried the comparison like typeof(item) == number, I got error as Not defined but I think, typeof(item) is number and also typeof(num) is number so, why can’t we compare as follows:

function sumOfArrayItems(...args){
var sum = 0;
for (const item of args)
{
    //var num = 1;
    if((typeof(item)) == (number)){
        sum += item;
    }
}
return sum;

I am a new learner and don’t understand this, tried searching but there’s no posts regarding this. Thnx

Why this code doesn’t redirect to the correct links?

I’m creating a simple game based in HTML and JS. The game asks you how many players are going to play, and the options are 1 player and 2 players. When click on “1 player” and then in the NEXT button, the game should redirect to the rps_2.html page, and when click on “2 player”, it should redirect to the rps2.html page.

Th`e problem is that when I click on any of the 2 options and click on the NEXT button, the page doesn’t redirect to any link, it stay there with no response.

I’m going to share the full code, so you can check it and tell me if there are any problem with it. Here is my code:

`<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords">
<meta name="description">
<meta charset="UTF-8">
<title>RPS Game</title>
<style>
    .header {
        background: black;
        color: white; 
        text-align: center;
        padding: 45px;
        font-size: 25px;
    }
    .body {
        font-family: Arial;
        text-align: center;
    }
    a {
        text-decoration: none;
        color: white;
    }
    button {
        font-size: 18px;
        font-family: Verdana;
        background-color: black;
        width: 250px;
        padding: 10px;
        margin: 18px;
        border: none;
        border-radius: 10px;
        cursor: pointer;
    }
</style>
</head>
<body class="body">
<div class="header">
    <a href="rps.html">
        <h1>Diego's Rock Paper Scissors</h1>
    </a>
</div>
<br>
<div style="border: 5px solid gray; width: 280px; height: 220px; margin: 0 auto;">
    <h2>Select number of players</h2>
    <form>
        <input type="radio" id="1p" name="player" value="1Player">
        <label for="1p">1 Player</label><br>
        <input type="radio" id="2p" name="player" value="2Player">
        <label for="2p">2 Player</label><br>
        <button id="next" style="color:white">NEXT</button>
    </form>
    <br>
    <a style="color: blue;" href="https://www.w3schools.com/html/html_head.asp">HOW TO PLAY?</a>
</div>
<script>
   const nextBtn = document.querySelector("#next");
let numOfPlayers;
nextBtn.addEventListener("click", function() {
const selectedRadio = document.querySelector('input[name="player"]:checked');
if (selectedRadio) {
    numOfPlayers = selectedRadio.value;
    if (numOfPlayers === "1Player") {
        window.location.href = "rps_2.html";
    } else {
        window.location.href = "rps2.html";
    }
} else {
    console.log("Please select number of players.");
}
});

</script>
</body>
</html>`

Thank you for your help!

I’ve changed the ‘name’ of the radio inputs (I put the 2 outputs with the same and different names and the error still there)

Is await a long time running async function in a request necessary?

So I have a request like this

handleUpdate1 = async(req, res, next) {
  await _asyncFuncWillRun10Minutes(req.body);
  return res.status(200).end();
}

So if a client make a GET request to this function, the client will wait around 10 minutes to get the response.

If I change the source to

handleUpdate2 =(req, res, next) {
  _asyncFuncWillRun10Minutes(req.body);
  return res.status(200).end();
}

The request will return immediately.

My question is the second func handleUpdate2, the execution will return immediately, what happens to _asyncFuncWillRun10Minutes?

Will it keep running until it finishes normally? Should I use await to wait until it finishes normally?

change language font style (fontFamily) [duplicate]

I want to change font style (fontFamily) when user change the language.

Ex:

if english => fontFamily = "name";
else fontFamily = "name";

my try:

if(language = "en"){
 document.getElementById("demo").style.fontFamily = "name"; 
}else{
 document.getElementById("demo").style.fontFamily = "name"; 
}

array length = 0 tensorflow.js

I have some tensorflow.js code that is supposed to read html code and assign it a certain value and I have a testing data set of only 4 elements where for trial purposes, 50% of the data set goes to training, 50% goes to testing. Whenever I start the process of running it, I get this error that says this.

this.binding.createTensor(info.shape, info.dtype, info.values);
                                     ^

Error: Shape does not match typed-array in bindData() (num_elements=2, array_length=0)
    at NodeJSKernelBackend.getInputTensorIds (/Users/HP/node_modules/@tensorflow/tfjs-node/dist/nodejs_kernel_backend.js:178:38)
    at NodeJSKernelBackend.executeSingleOutput (/Users/HP/node_modules/@tensorflow/tfjs-node/dist/nodejs_kernel_backend.js:219:73)
    at Object.kernelFunc (/Users/HP/node_modules/@tensorflow/tfjs-node/dist/kernels/Reshape.js:34:27)
    at kernelFunc (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4651:32)
    at /Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4711:27
    at Engine.scopedRun (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4516:23)
    at Engine.runKernelFunc (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4707:14)
    at Engine.runKernel (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4580:21)
    at reshape_ (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:9384:19)
    at Object.reshape__op [as reshape] (/Users/HP/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:5555:29)

The error might be occurring in the preprocessing step of the code, which here is the entire preprocessing step.

async function preprocessHtml(html) {
    try {
      const strippedHtml = html.replace(/<[^s>]+[^>]*>/g, '').replace(/</[^>]+>/g, '').replace(/s+/g, '');
      const inputTensor = tf.tensor(strippedHtml.split(' '));
      return inputTensor;
    } catch (error) {
      console.error(`An error occurred while preprocessing the HTML: ${error}`);
      const inputTensor = tf.zeros([1, 2]);
      return inputTensor;
    }
  }
  
  
  async function* dataGenerator(trainingData) {
    for (const item of trainingData) {
      try {
        const html = await getHtml(item.url);
        const inputTensor = await preprocessHtml(html);
        const labelTensor = tf.tensor([item.label]);
        yield {
          input: inputTensor,
          label: labelTensor
        };
      } catch (error) {
        console.error(`An error occurred while preprocessing the data for ${item.url}: ${error}`);
        continue;
      }
    }
  }

I have tried changing the input shape and batch size, but nothing has worked and the error has stayed the same no matter what I try.

Javascript – add string before link using document.createElement

I’m creating a callout using the Apple MapKit JS using document.createElement which is working by adding elements from an array that contains the data. I would now like to add a string in front of some of the elements – I have it been able to do this successfully for non links thanks to this answer but I can’t work out how to do this for links.

Here’s how the callout currently looks:

enter image description here

I would like to add some text before the website links (e.g. ‘Main’) that aren’t part of the clickable link. Here’s the code for the callout that gets created:

// Landmark annotation callout delegate
var calloutDelegate = {
// Return a div element and populate it with information from the
// annotation, including a link to a review site.
calloutContentForAnnotation: function(annotation) {
    var element = document.createElement("div");
    element.className = "review-callout-content";

    var link = element.appendChild(document.createElement("a"));
    link.href = annotation.landmark.url;
    link.textContent = "website";
    
    var phone = element.appendChild(document.createElement("p"));
    //phone.textContent = annotation.landmark.phone;
    phone.textContent = `Phone: ${annotation.landmark.phone}`;

    var contact = element.appendChild(document.createElement("a"));
    contact.href = annotation.landmark.url2;
    contact.textContent = "contact";

    // Add more content.
    element.style.width = "240px";
    element.style.height = "100px";
    return element;
}

separate each row into one table

I built the search engine to search the value from the spreadsheet. But how can i display one row into one table because i want to print it separately. For now, my code like this:

function createTable(dataArray) {
            if(dataArray && dataArray !== undefined && dataArray.length != 0){
              var result = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
                           "<thead style='white-space: nowrap'>"+
                             "<tr>"+                 
                              "<th scope='col'>Timestamp</th>"+
                              "<th scope='col'>Part Number</th>"+
                              "<th scope='col'>SAP Part Number</th>"+
                              "<th scope='col'>Work Order</th>"+
                              "<th scope='col'>Production Line</th>"+
                              "<th scope='col'>IPQC</th>"+
                              "<th scope='col'>Process</th>"+
                              "<th scope='col'>Operator/Set-up Technician</th>"+
                              "<th scope='col'>Cable/Wire/Tube SAP Part Number</th>"+
                              "<th scope='col'>Lower Spec Limit</th>"+
                              "<th scope='col'>Upper Spec Limit</th>"+
                              "<th scope='col'>Measurement Record</th>"+
                              "<th scope='col'>Equipment ID</th>"+
                            "</tr>"+
                          "</thead>";
              for(var i=0; i<dataArray.length; i++) {
                  result += "<tr>";
                  for(var j=0; j<dataArray[i].length; j++){
                      result += "<td>"+dataArray[i][j]+"</td>";
                  }
                  result += "</tr>";
              }
              result += "</table>";
              var div = document.getElementById('search-results');
              div.innerHTML = result;
            }else{
              var div = document.getElementById('search-results');
              //div.empty()
              div.innerHTML = "Data not found!";
            }
          }

the output:

enter image description here

Is it possible to make it separate each row become one table. So it will be two table there

Show Hide Menu Toggle Button Opacity and Display Block

im trying to show hide toggle this submenu button trigger
and was trying to have it animated by opacity and have the display none so that the height adjusts accordingly and smoothly upon open/close.

Need help, Thank you.

Javascript



var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function () {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.opacity === "100" , dropdownContent.style.display === "block"
       ) {
      dropdownContent.style.opacity = "0" , dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.opacity = "100" , dropdownContent.style.display = "block";
    }
  });
}

https://jsfiddle.net/ekofz58t/

como puedo insertar una lista de productos en un foreach en laravel 8 [closed]

Este es mi codigo del controlador
foreach ($request->id_productos as $resultado) {
orden::create([‘id_productos’ => $resultado]);

}
esta es de mi vista
foreach($cartCollection as $item)
productos_id}}” id=”id_producto”>

                         <input type="show" name="nombre[]" value="{{$item->nombre}}" id="nombre">

@endforeach

tengo 2 productos pero Solo me inserta el ID de mis dos productos, quisiera se insertara el nombre.

quisiera que se insertara mis dos productos en la bd en laravel 8 con todos sus datos, nombre,cantidad,etc

Unit test socket – javascript

How can I test this socket in javascript?

  socketConnect(uri) {
    this.wS = new WebSocket(uri);
    this.wS.addEventListener('open', this._openSocket.bind(this));
    this.wS.addEventListener('message', this._messageSocket.bind(this));
    this.wS.addEventListener('close', this._closeSocket.bind(this));
  }

I would like to test this socket using sinon. So far I haven’t been able to get it to work.