2017-01-06 23 views
0

我有2個功能。一個從checkboxes增加值,另一個將值從radioboxes增加到var tot放射性元素只增加變化值,但不會減去

問題是radiobox只會將值增加到var tot,但不會在未選中時減少。
我沒有這個問題,直到我作用域了var tot,但它必須這樣做,這兩個功能可以訪問它。這裏是行動的問題,一個代碼示例:

$(':checkbox:checked').prop('checked', false); 
 
$('input[type="radio"]:checked').prop('checked', false); 
 

 
$(document).ready(function() { 
 
    var tot = 0; 
 
    $('#usertotal').text('0 SEK') 
 

 
    $('input:checkbox').change(function() { 
 
    if (!$(this).is(':checked')) { 
 
     tot -= parseInt($(this).val()); 
 
    } else { 
 
     tot += parseInt($(this).val()); 
 
    } 
 
    $('#usertotal').text(tot + ' SEK') 
 
    }); 
 

 
    $('input[type="radio"]').change(function() { 
 
    if ($(this).is(':checked')) { 
 
     tot += parseInt($(this).val()); 
 
    } else if (!$(this).is(':checked')) { 
 
     tot -= parseInt($(this).val()); 
 
    } 
 
    $('#usertotal').text(tot + ' SEK') 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
 

 
<input type="radio" name="radioName" value="160 Yes">till 20 
 
<input type="radio" name="radioName" class="someclass" value="5 Yes"> 20 
 
<input type="checkbox" name="" value="29 Yes">BV 
 

 
<div class="col-lg-4 col-mg-3 col-sm-12 col-xs-12 calculation-window"> 
 
    Totalt: <span id="usertotal"></span> 
 
</div>
的jsfiddle:https://jsfiddle.net/ys1b9Lwv/12/

+2

這已在其他問題進行了討論。 [單選按鈕「更改」事件僅在激活時觸發,而不是在停用時觸發。](http://stackoverflow.com/a/18034498/1679849)您可能會發現在每次onchange事件中重新開始重複計算會更容易。 –

回答

1

我們不能得到單選框取消選擇。所以我的解決方案是由我們自己解除選擇,並確定已經選定的收音機。我正在使用課堂來實現它。

$('input[type="radio"]').change(function() { 

     tot += parseInt($(this).val()); 
    $(this).addClass("sel"); 
    $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); 
    $('#usertotal').text(tot + ' SEK') 
    }); 
    $('input[type="radio"]').bind('deselect', function(){ 
    if($(this).hasClass("sel")) 
    { 
    $(this).removeClass("sel"); 
     tot -= parseInt($(this).val()); 
     $('#usertotal').text(tot + ' SEK') 
    }}); 
3

問題似乎是單選按鈕在未選中時不觸發更改事件。將記錄添加到無線電更改事件中可以確認這一點。

有解決這幾個方面,但我認爲最優雅的是總的計算重構爲一個單獨的函數,它檢查所有參與金額/總組件的值。

我拿出this solution

var tot = 0; 
$('#usertotal').text('0 SEK'); 

var update_tot = function() { 
    tot = 0; // reset 

    // sum of inputs that are checked 
    $('input:checkbox,input[type="radio"]').each(function(){ 
    if ($(this).is(':checked')) 
     tot += parseInt($(this).val()); 
    }); 

    $('#usertotal').text(tot + ' SEK'); 
}; 

$('input:checkbox,input[type="radio"]').change(update_tot); 

這方面的一個清潔重寫可能是:

var tot = 0; 
$('#usertotal').text('0 SEK'); 

$('input:checkbox,input[type="radio"]').change(function() { 
    tot = 0; // reset 

    // sum of inputs that are checked 
    $('input:checkbox,input[type="radio"]') 
    .filter(':checked') 
    .each(function(){ 
     tot += parseInt($(this).val()); 
    }); 

    $('#usertotal').text(tot + ' SEK'); 
});