简体   繁体   中英

JavaScript onclick function won't execute

I'm new to JavaScript and can see nothing wrong with this code. It's supposed to calculate how much the items are. How can I get this to work?

(I've looked through a lot of posts with similar titles but couldn't figure out the issue.)

 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>

You have a typo on this line, it's innerHTML not innerhtml :

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

Should be:

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

You need to use innerHTML instead of innerhtml and put your script inside <script></script>

Example: onclick event

The calculate function is being executed. The problem instead lies within the following line:

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

When setting the HTML value of an element, you need to use innerHTML . Notice the capitalisation.

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

Change that, and you're golden.

I remember when I was new for a javascript. Oohh! Mamamia! Here I will provide you an example and if you'll catch the idea then you'll get the right way. Do not get scared, its very simple but it will give you the idea of how should the javascript looks like.

I could be much happier if somebody explained to me that on my beginning.

At the end, you'll find the answer to your question.

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 your browser console to find out where the error happens. Do not use onClick="" instead use document.getElementById('myButtonClick').addEventListener("click",calculateFactory); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM