我有四个文本字段,用户可以在其中插入值。对于前两个输入字段,它会计算将两个字段加在一起。这个想法是获取每个字段的百分比值。因此,一旦有一个值,我们就除以总数,然后乘以 100 以获得每个文本字段的百分比值。
一切正常!
但是,如果用户手动进入并添加白天百分比,它应该自动计算夜间百分比(或相反),只需获取该值并减去 100。
每次我更改值时,它都会恢复为旧版本。
var day_value, night_value, day_percentage, night_percentage;
$('#day_kwh').on('input', function() {
day_value = this.value;
});
$('#night_kwh').on('input', function() {
night_value = this.value;
});
$('.storage').on('change', function() {
//console.log(day_value + night_value);
if (typeof day_value != 'undefined' && typeof night_value != 'undefined') {
total = parseInt(day_value) + parseInt(night_value);
console.log('total value: ' + total);
day_value = (day_value / total) * 100;
console.log('day value: ' + day_value);
night_value = (day_value / total) * 100;
console.log('night value: ' + night_value);
$('#day_percent').val(day_value);
$('#night_percent').val(night_value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="storage">
Day kWH:
<input type="text" name="day_kwh" id="day_kwh">
<br>Night kWH:
<input type="text" name="night_kwh" id="night_kwh">
<br>Day %:
<input type="text" name="day_percent" id="day_percent">
<br>Night %:
<input type="text" name="night_percent" id="night_percent">
<br>
<input type="submit" value="Submit">
</div>
最佳答案
您需要添加额外的代码来检查更改的控件是否为day_percent
$('.storage').on('change', function(e) {
//console.log(day_value + night_value);
if(e.target && $(e.target).attr('id') == 'day_percent'){
/* Write the logic for your calculation you want */
}
else
if (typeof day_value != 'undefined' && typeof night_value != 'undefined') {
total = parseInt(day_value) + parseInt(night_value);
console.log('total value: ' + total);
day_percentage = (day_value / total) * 100;
console.log('day value: ' + day_value);
night_percentage = (night_value / total) * 100;
console.log('night value: ' + night_value);
$('#day_percent').val(day_percentage);
$('#night_percent').val(night_percentage);
}
});
关于javascript - 值更改后文本值保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425525/