Soy nuevo en JavaScript y no puedo ver nada malo con este código. Se supone que calcula cuánto son los artículos. ¿Cómo puedo hacer que esto funcione?

(He revisado muchas publicaciones con títulos similares, pero no pude resolver el problema).

function calculate() {

var total = 0;

if (document.getElementById('cb1').checked == true)

{ total = total + 25;}

if (document.getElementById('cb2').checked == true)

{ total = total + 50;}

if (document.getElementById('cb3').checked == true)

{ total = total + 75;}

if (document.getElementById('cb4').checked == true)

{ total = total + 100;}

document.getElementById('output').innerhtml = '€' + total;

}
#output {
width: 400px;
font-size: 2em;
height: 1.5em;
line-height: 1.5em;
background: #dddddd;

}
<h1> Checkout </h1>

<p> Select a product below:</p>
<p>Product 1 <input type ="checkbox"  id="cb1"></p>
<p>Product 2 <input type ="checkbox"  id="cb2"></p>
<p>Product 3 <input type ="checkbox"  id="cb3"></p>
<p>Product 4 <input type ="checkbox"  id="cb4"></p>


<button onclick="calculate()">Calculate</button>

<div id="output"> 0 </div>
0
user7705760 31 oct. 2017 a las 01:43

3 respuestas

La mejor respuesta

Tiene un error tipográfico en esta línea, es innerHTML no innerhtml:

document.getElementById('output').innerhtml = '&euro;' + total;

Debe ser:

document.getElementById('output').innerHTML = '&euro;' + total;
1
AquaticFire 30 oct. 2017 a las 22:46

Debe usar innerHTML en lugar de innerhtml y poner su script dentro de <script></script>

Ejemplo: evento onclick

1
DenysM 30 oct. 2017 a las 22:54

Recuerdo cuando era nuevo para un javascript. Oohh! ¡Mama Mia! Aquí le daré un ejemplo y si capta la idea, obtendrá el camino correcto. No se asuste, es muy simple, pero le dará la idea de cómo debería ser el Javascript.

Podría ser mucho más feliz si alguien me lo explicara en mi comienzo.

Al final, encontrará la respuesta a su pregunta.

Html:

    <p>Product 1 <input type="checkbox"  id="cb1"></p>
    <p>Product 2 <input type="checkbox"  id="cb2"></p>
    <p>Product 3 <input type="checkbox"  id="cb3"></p>
    <p>Product 4 <input type="checkbox"  id="cb4"></p>
    <button id="myButtonClick">calculate</button>

Javascript:

        /*
         * First of all, try to think next way.
         * In javascript each element, let's say Integer or String 
         * IS an Object. That means it supposed to work with 
         * anything as we work with an object.
         * 
         * I could be much happier if somebody explained
         * me that on my beginning.
         */
        var classCalator = function(){

            var total = 0;

            /*
             * use function recursively instead of useing a bunch of if's
             * of foeach or for or ...
             */
            var isChecked = function(element){
                var elementID = element[0];
                return !!(document.getElementById(elementID).checked);
            };

            var totalize = function(element){
                var elementNumberForSum = element[1];
                total =+ elementNumberForSum;
            };

            /*
             * use function recursively instead of useing a bunch of if's
             * of foeach or for or ...
             */
            this.calculate = function(configElements){
                var elements = configElements;
                var element = elements[0];
                if( !!element && isChecked(element)){
                    totalize(element);
                    //remove first element that is already prepared
                    elements.shift();
                    //recursively do same staff with each element from conf
                    this(elements);
                }
                //return total that we were looking for
                return total;
            };
        };

        var calculatorConfig = function(){
            /*
             * Reference to this class (config function) reference to it self
             * to get access to it in the children classes;
             * 
             * @type Object
             */
            var conf = this;

            /*
             * array of element that you want to prepare to not use 
             * is statements if(){} is evil you understand that later but 
             * now learn and write this way.
             * 
             * @type Array 
             */
            var elemntsConfig = [];

            /*
             * That is an children class (object) of the our 
             * config class (function). It just push all elements to array.
             * 
             * @return null 
             */
            this.setElement = function(elementID, specificNumber){
                var record = [elementID, specificNumber];
                elemntsConfig.push(record);
            };

            /*
             * Just retrive our elemntsConfig
             * 
             * @return Array 
             */
            this.getConfig = function(){
                return elemntsConfig;
            };
        };


        var calculateFactory = function(){

            var calculator = new classCalator();
            var configuration = new calculatorConfig();
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //Now you can add as many checkboses 
            //as you want and no need more ifs'
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            configuration.setElement('cb1', 10);
            configuration.setElement('cb2', 10);
            configuration.setElement('cb3', 20);
            configuration.setElement('cb4', 10);
            //here I just retrive my classes
            var config = configuration.getConfig();
            //and initialize calculations
            var total = calculator.calculate(config);

            console.log(total);
        };

        var myButtonClick = document.getElementById('myButtonClick');

        myButtonClick.addEventListener("click", calculateFactory);

Use la consola de su navegador para averiguar dónde ocurre el error. No use onClick="" en su lugar use document.getElementById('myButtonClick').addEventListener("click",calculateFactory);.

0
Tudor Corcimar 31 oct. 2017 a las 17:12