Price calculation with radio buttons
Solved
Paela318
Posted messages
17
Status
Member
-
prosthetiks Posted messages 1309 Status Member -
prosthetiks Posted messages 1309 Status Member -
```javascript
function calculerPrix() {
let prixFinishing = document.querySelector('input[name="finition"]:checked').value;
let prixFormat = document.querySelector('input[name="format"]:checked').value;
let prixSupport = document.querySelector('input[name="support"]:checked').value;
let prixTotal = parseInt(prixFinishing) + parseInt(prixFormat) + parseInt(prixSupport);
document.getElementById('prix').innerText = prixTotal + " €";
}
document.querySelectorAll('input[type="radio"]').forEach((input) => {
input.addEventListener('change', calculerPrix);
});
// Calcul initial pour afficher le prix par défaut
calculerPrix();
```
function calculerPrix() {
let prixFinishing = document.querySelector('input[name="finition"]:checked').value;
let prixFormat = document.querySelector('input[name="format"]:checked').value;
let prixSupport = document.querySelector('input[name="support"]:checked').value;
let prixTotal = parseInt(prixFinishing) + parseInt(prixFormat) + parseInt(prixSupport);
document.getElementById('prix').innerText = prixTotal + " €";
}
document.querySelectorAll('input[type="radio"]').forEach((input) => {
input.addEventListener('change', calculerPrix);
});
// Calcul initial pour afficher le prix par défaut
calculerPrix();
```
10 answers
-
Hello, I will help you, I will review your code and get back to you.
-
-
Here you go!
<html> <head> <title></title> </head> <body> <div id="choix"> <legend>1) Choice of finish</legend> <p><!-- Radios --> <input type="radio" name="finition" checked="checked" id="plexi" value="20"/> <label for="a">Plexiglass</label><br/> <input type="radio" name="finition" id="alu" value="30" /> <label for="b">Aluminum / Dibond</label><br/> </p> <legend>2) Choice of format (portrait)</legend> <p><!-- Radios --> <input type="radio" name="format" checked="checked" id="petit" value="15" /> <label for="c">60x60 cm</label><br/> <input type="radio" name="format" id="moyen" value="25" /> <label for="d">100x100 cm</label><br/> <input type="radio" name="format" id="grand" value="35" /> <label for="e">140x140 cm</label><br/> </p> <legend>3) Choice of support</legend> <p><!-- Radios --> <input type="radio" name="support" checked="checked" id="toile" value="40" /> <label for="f">Canvas</label><br/> <input type="radio" name="support" id="bois" value="60" /> <label for="g">Wood</label><br/> </p> Price: <span id="prix"></span> <button onclick="superCalculateur.calculeLePrixDeMalade()">Calculate</button> </body> <script type="text/javascript"> var superCalculateur = { calculeLePrixDeMalade: function(){ var total = 0; // Get all inputs var elements = document.getElementsByTagName('input'); // Loop through the retrieved elements to process each input separately for(var element in elements){ var current = elements[element]; // Check if input is an object, that it is of type radio (there could be inputs of other types, like text or password), and finally that it is checked. if(typeof current == 'object' && current.getAttribute('type') == 'radio' && current.checked){ // This code will be executed only by radio type inputs that are checked. We retrieve their value and add it to the current value of the total variable (the += is a shortcut for total = total + current.value) total += parseFloat(current.value); } } // Once the loop is finished, display the total variable content alert('Total: ' + total); } } </script> </html> -
I'm glad it's exactly the result I wanted! If you have a bit of time to spare, I would like to ask you a few questions about the code (I know I'm annoying but I like to understand everything lol).
- First of all, why did you create the first variable superCalculateur, what is its purpose?
- Next, I don't understand how the loop works :/
Thanks again for your help! -
I created this first variable to encapsulate my function; it is not mandatory, but it helps to better organize your code and avoid conflicts with functions of the same name that may be declared in other scripts present on the same page.
There are function names that are relatively common (like getName()) which we might accidentally redeclare. Therefore, thanks to this system, I can declare a function of that name even if it already exists in a previously loaded script.
It's a sort of namespace (I refer you to Google for a complete definition of namespaces, available in most recent languages)
Now, let's break down the behavior of the loop:
We start by retrieving the inputs with this line:var elements = document.getElementsByTagName('input');
elements is now an array where each entry contains a different input.
In practice, here is the content of the elements variable:0: input#plexi 1: input#alu 2: input#petit 3: input#moyen 4: input#grand 5: input#toile 6: input#bois length: 7
We can see that from index 0 to 6, there are the different inputs of the page. At index 7, which has the key "length," we find the total length of the array. This entry is automatically added by the "getElementsByTagName" method, which will annoy us during our loop; we will revisit this in due time.
The loop:
The linefor(var element in elements){. If we were to translate it into French, it could be phrased as: For each element present in elements, enter the loop.
The loop will therefore execute 8 times, and the variable element (which is created on the fly) will contain the key of the array for the current element each time.
Here are the values of element for each iteration through the loop:
Iteration 1: element = 0
Iteration 2: element = 1
Iteration 3: element = 2
Iteration 4: element = 3
Iteration 5: element = 4
Iteration 6: element = 5
Iteration 7: element = 6
Iteration 8: element = length
Now let's dive into the loop.
We find this line:
var current = elements[element];
So on the first pass through the loop, we will retrieve the value found in elements at index 0.
If we refer back to the content of our elements array, we see that at index 0 we find: input#plexi
The next line is:
if(typeof current == 'object' && current.getAttribute('type') == 'radio' && current.checked){
We have 3 conditions separated by & (AND). Therefore, all three must be met for us to enter the condition.
Suppose our input#plexi is checked:
The variable is of type "object," it is of type "radio," and it has the attribute "checked."
So we retrieve its value with the linetotal += parseFloat(current.value);
and we proceed this way for all the elements of the array.
There's just one subtlety: We saw that our elements array contained the length of the array (at index length). This entry is not an object; it's a string (a character string), which is why I included the condition typeof current == 'object'. Without it, I would have attempted to call the getAttribute function on a string, which does not possess it, causing my script to crash.
I hope this explanation is clear enough :/ -
I had to read it three times to understand, but now I got it. Thank you for going through so much trouble to explain all of this to me; it will help me :) Also, no matter how much I read the references for ParseFloat and ParseInt, I still can't quite grasp their function. If you could clarify this point for me, I would understand everything completely! :)
-
<html> <head> <title></title> </head> <body> </body> <script type="text/javascript"> var superCalculator = { calculateTheCrazyPrice: function(){ var stringValue = '10'; var intValue = 10; var floatValue = 10.5; var v0 = stringValue + intValue + floatValue; var v1 = parseInt(stringValue) + parseInt(intValue) + parseInt(floatValue); var v2 = parseFloat(stringValue) + parseFloat(intValue) + parseFloat(floatValue); alert('Without parsing:' + v0 + ' With parseInt: ' + v1 + ' with parseFloat: ' + v2); } } superCalculator.calculateTheCrazyPrice(); </script> </html> -
I declare three variables:
var stringValue = '10'; var intValue = 10; var floatValue = 10.5;
stringValue is a string (it is defined with quotes)
intValue is an integer (or int)
floatValue is a floating-point number (or float)
The parseInt function allows you to convert a variable into an integer
The parseFloat function allows you to convert a variable into a floating-point number
I’m going to make three different calculations:
#1var v0 = stringValue + intValue + floatValue;
the plus sign also serves as a concatenation operator and since stringValue is a string, it will concatenate the three values and we will get the value: 101010.5
That’s not what we want! :(
Let’s try with parseInt!
#2var v1 = parseInt(stringValue) + parseInt(intValue) + parseInt(floatValue);
stringValue now equals 10 and no longer '10' (It has been converted into an integer)
intValue = 10
floatValue = 10 (we lost the decimal, we just converted it into an integer)
The result of that is 30, which is wrong! :(
#3 Now let's test parseFloat, and by converting all our variables with it, we keep the precision of floatValue while making the calculation possible. -
Oh thank you! You really put in a lot of effort, it's nice to see that people still care so much on forums :) Anyway, you managed to answer my topic and explain everything to me, thanks again :)
-
You're welcome, my pleasure :) Have a good continuation!