Question

I have made JavaScript code using the fiddle.com website. But in fiddle I can only make it work by using the

no wrap (body)

option. I'm not sure what this option does. The link for the Fiddle is here. I added this script to my Blogger blog, but it would not work.

Code

function getTotal(){
    var form = document.theForm;
    var inputs = form.getElementsByTagName('input');
    var length = inputs.length;
    var total = '0';

    for (i = 0; i<length-1; i++){
        if(inputs[i].type == 'radio'){
            var checked = inputs[i].checked?1:0;
            if(checked){
                var value = inputs[i].value.split("~~")[0];
                total -= -value;
            }
        }
    }
    document.getElementById('totalspan').innerHTML="Toplam Fiyat: "+ total + " tl"
    total='0';
}

The script is to calculate a total price of the selections. You can see it in the fiddle. Also, I have it on Blogger, but as I said it's not working.

The link to my blog is here.

Was it helpful?

Solution

no wrap (body) means that your script will be inserted in new script tag inside body tag, no wrap (head) means that your script will be inserted in new script tag inside head. You can read about it on jsFiddle help

Other options will wrap your JS code inside particular DOM event handlers (onLoad and onDomReady)

Script errors on your site tells me that calculateTotal is not defined, so please check your naming.

Why do you use string when calculating total? You can safely use native JS parseInt funciton.

Another point that using form click event is wrong, you should use change event of your inputs.

Simplest option for you is to use jQuery like this:

$('[name="CPU"], [name="OperatingSystem"], [name="Case"]').on('change', updateTotal);

function updateTotal {
   var total = 0;
   // calculate your total here
   $('#totalspan').text(total);
}

Please check my 5-min fiddle: http://jsfiddle.net/GDXuS/5/

You could also use data- attributes to store price or any other data (see on jQuery site).

And I'm advice you to study some programming languages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top