Search code examples
javascriptradio-buttondom-eventsonchange

How to get the value of the prev selected radio button


Given this markup http://jsfiddle.net/ARPCw/ how can I update the total on change?

The problem is that I need the value (data-price) of the previous selected radio button, so I can subtract it to the total amount before to add the new one.


Solution

  • example fiddle: http://jsfiddle.net/ARPCw/5/

    relevant js

    var cb = document.getElementsByTagName('input'),
        total = document.getElementById('tprice');
    
    for (var i = 0; i < cb.length; i++) {
        (function(c) {
           c.onclick = function() {
              var bp = 200;
              for (var i = 0; i < cb.length; i++) {
                 if (!!cb[i].checked) {
                   bp += +cb[i].getAttribute('data-price');  
                 }
              }
              total.innerHTML = bp;
           }
        }(cb[i]))        
    }