Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP.

On the product details page, users can add products to their cart, so I show the total cart value.

I need the total amount displayed in a decimal number format (10,2).

Currently, when a user clicks "Add to cart" and the product price is $12.00, only the number 12 is shown in the Counter div.

<span>
<a href="cart.php" class="text-white">
<i  class="fa fa-shopping-cart p1"  data-count="10" data-currency="&euro;" id="total"></i>
</a>
</span> 
 .p1[data-count]:after{
  position:absolute;
  right:1%;
  top:1%;
  content: attr(data-count);
  font-size:10px;
  padding:.2em;
  line-height:1em;
  color: white;
  background:#21468b;
  text-align:center;
  width: 100%;
  font-weight:normal;
}
<script>
var theTotal = '0';
var ProductSellingPrice = '12.00'

$('#insert').click(function(){

   theTotal = Number(theTotal) + Number(ProductSellingPrice);

    $('#total').attr('data-count', theTotal);

});


</script>

When the "insert" button is clicked, the existing total and current product price are added together. If the cart is empty, the p1 element does not display anything, so I want it to always show zero when empty or zero. For a product priced at $12.00, it should display 12. If the price is $12.50, then 12.50 should be displayed.

I want to ensure that the number displayed is always in decimal format and include the currency symbol using a data attribute.

I have resolved the issue with displaying decimals thanks to @Simone, but I have not been able to find a solution for displaying the currency symbol before the value using a data attribute.

Answer №1

To ensure the output displays as 12.00 instead of 12, it is necessary to utilize Number.prototype.toFixed()

In order to achieve this, each individual product total (quantity * price) must be converted into a Float number. When calculating the total sum, apply the following:

Number.parseFloat(total).toFixed(2); // two decimal

For instance:

var quantity = 10;
var price = 11;
var tot = parseFloat(quantity * price).toFixed(2);
console.log(tot); // "110.00"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...

What is the reason behind re-rendering pages specifically for error messages in express and nodejs?

In the world of web development, it is commonly accepted practice to re-render a page to display error messages and redirect to show success messages. While implementing this principle in my code using express js, I have encountered a few challenges. For ...

What is the best way to extract a portion of a JSON string?

this.on('success', function(file, responseText) { var theID = JSON.stringify(responseText); alert(theID); window.location.href = ('want to put something here'); }); The ...

Ways to deactivate webfonts specifically for Safari

Recently, I have been experiencing font crashing issues with the webfont on Safari. Is there a way to disable this font specifically for this browser? ...

Is there a way to ensure that GIFs in jQuery Mobile always start from the beginning?

My cross-platform mobile app built with jQuery Mobile is a small quiz application. After each correct or wrong answer, I display a 3-second GIF. Currently, I have set up the code to show the GIF for 3 seconds before moving on to the next page: else if ($. ...

What is the best way to save high-resolution images created with HTML5 canvas?

Currently, there is a JavaScript script being used to load and manipulate images using the fabricjs library. The canvas dimensions are set to 600x350 pixels. When smaller images are uploaded onto the canvas and saved as a file on disk, everything works c ...

Banner Text Alignment Issue: Uneven Left Alignment

Struggling to achieve consistent text alignment on a ribbon banner? Check out the issue I'm facing and see if you have any suggestions on fixing it: Link to Codepen Main issues: The first line of text appears slightly more indented on the left side ...

Utilizing jQuery to retrieve the chosen option and then set it as the selected

I created a form that automatically populates shipping fields with the same information as billing fields if the user wants to use identical details. However, I am encountering an issue with the title section - there is a select options list including titl ...

`returning a functional component directly from a component's event listener`

Recently, I started exploring React and came across an issue with React Router integration. I have a React menu component that includes hyperlinks in a sidenav for navigation to other components. However, the standard React Routing method doesn't see ...

PhoneGap iOS application storing outdated information

My Phonegap 2.1 app running on iOS 6, with jQuery 1.7.2 and JQMobile 1.1.1 libraries, is experiencing an issue where old data from ajax responses gets cached if the app is unused for a few days. The only way to resolve this issue is by reinstalling the a ...

Incorporate Select2 functionality within the Angular2 application

I'm currently working on incorporating the Select2 plugin into my Angular2 application. Successfully, I have managed to set up select2 and transform my multiple select fields as expected. However, I am now facing a challenge in retrieving the selected ...

"Enhancing website performance with JavaScript by leveraging DOM innerHTML scrollHeight

Here is a two-part question I have: The first part of the question: test A: t1 = new Date().getTime(); for (i=0; i<205; i++) { document.getElementById("divTest").innerHTML = sText; } t2 = new Date().getTime(); ...

Failure to retrieve fax API data using Twilio's Node.js HTTP requests

Looking to implement fax receiving using Twilio API. This is an excerpt from my index.js file: // const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); c ...

Inserting information into a MySQL database using a dynamic jQuery-generated form

i'm attempting to input data into MySQL from a dynamic form utilizing jQuery. Just to clarify, I am working with Twitter Bootstrap. Currently, I managed to insert "rows" but without any data. The most helpful resources I came across are located here f ...

Is it feasible to select the last child of an input without having to specify the submit

Here is a portion of the HTML code I am currently testing: <form action="#" method="post> <input name="username" type="text" placeholder="Username" /><br /> <input name="password" type="password" placeholder="Password" />&l ...

Need to import Vue from a JavaScript file

I am relatively new to modern frontend development tools. After installing Nodejs and NPM, I successfully downloaded packages such as "jquery" and everything was working fine. However, when I installed Webpack (version 2) and created a demo configuration f ...

What is the method to fetch a JSON URL data set (using Ajax and jQuery) in order to generate a dynamic chart display that updates automatically on a Wordpress webpage?

I have downloaded all the necessary plugins for Wordpress, but unfortunately, the data is not displaying. Below is the code I am using to embed the data onto a page: <script> <div class="result"></div> <script type="text/javascri ...

Proper techniques for storing element count in Protractor

I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional. My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promi ...

Tips on customizing KendoUI-Dialog titlebar using CSS for a single component

I am struggling with styling the KENDO UI dialog in a unique way: Imagine I have a component named WatComponent. Inside this component, When the user clicks the "Forbidden" button, my goal is to make a warning styled dialog appear, with a yellow/orange ...

Technique for eliminating hyphens and capitalizing the initial words

I have a key named some_name that I want to transform into Some Name. Is there a way to remove the dash and capitalize the first letter of each word in the key? var data = $(this).serializeObject(); $.each(data, function(key, val) { var tablefeed = $(&ap ...