我有3个输入文件
我想输入两个输入第三个拉动自动推杆
<input id='cpercentage' name='first'>
<input id='epercentage' name='second'>
<input id='mpercentage' name='third'>
我输入第二个30%的前20%
在第三个中它将自动显示50%剩余的100%
(20%+ 30%) - 100%= 50% 如何在javascript中做到这一点?
我尝试了这个,但它没有工作
$(函数(){
$('#cpercentage').on('input', function() {
calculate();
});
$('#epercentage').on('input', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#cpercentage').val());
var pEarned = parseInt($('#epercentage').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = (100-(pEarned+pPos)).toFixed(3);
}
$('#mpercentage').val(perc);
}
});
答案 0 :(得分:2)
我会将事件设置为change
$('#cpercentage').on('change', function() {
你的计算也是错误的
perc = (100- (pEarned+pPos)).toFixed(3);
将%添加到计算结果中,您只需要执行此操作:
$('#mpercentage').val(perc+"%");
结合它就像这样:
$('#cpercentage').on('change', function() {
calculate();
});
$('#epercentage').on('change', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#cpercentage').val());
var pEarned = parseInt($('#epercentage').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = (100- (pEarned+pPos)).toFixed(3);
}
$('#mpercentage').val(perc+"%");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='cpercentage' name='first'>
<input id='epercentage' name='second'>
<input id='mpercentage' name='third'>
要使用此选项,您只需要正确更改标记:
$('#cpercentage').on('change', function() {
calculate();
});
$('#epercentage').on('change', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#cpercentage').val());
var pEarned = parseInt($('#epercentage').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = (100- (pEarned+pPos)).toFixed(3);
}
$('#mpercentage').val(perc+"%");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='cpercentage' name='first'>
<option>10%</option>
<option>15%</option>
<option>30%</option>
</select>
<select id='epercentage' name='second'>
<option>10%</option>
<option>15%</option>
<option>30%</option>
</select>
<input id='mpercentage' name='third'>
答案 1 :(得分:1)
两个评论:
select
事件。perc = (100 - (pEarned + pPos)).toFixed(3);
答案 2 :(得分:0)
keyup
,change
至select
Math.abs()
来toFixed()
以下是代码:
$(function() {
$('#cpercentage').on('keyup', function() {
calculate();
});
$('#epercentage').on('change', function() {
calculate();
});
function calculate() {
var pPos = parseInt($('#cpercentage').val());
var pEarned = parseInt($('#epercentage').val());
var perc = "";
if (isNaN(pPos) || isNaN(pEarned)) {
perc = " ";
} else {
perc = Math.abs((pEarned + pPos) - 100);
}
$('#mpercentage').val(perc + '%');
}
});
change
和keyup
之间存在一点差异,您可以随意选择。