正在寻找一种使用javascript实时计算3个输入字段中的2个的方法



我正在尝试创建一个简单的应用程序,并希望显示三个输入。这将是一种计算市值/股价/可用股份的表格。其公式为{shares-available * share-price = market capitalization}。我希望在每个输入中都有伪文本,并允许用户添加任意两个值,然后自动计算第三个值。我理解HTML和CSS部分,但我一直在用JavaScript尝试很多不同的东西,不断遇到我没有预料到的墙,不得不从头开始(无论如何,我从来没有真正做到这一点(。

我的HTML:

<div class="container center">
<div class="row">
<div class="col-100">
<input data-ctp type="text" id="ctp" name="firstname" placeholder="Coin/Token Price">

</div>
</div>
<div class="row">
<div class="col-100">
<input data-cs type="text" id="cs" name="lastname" placeholder="Circulating Supply">

</div>
</div>
<div class="row">
<div class="col-100">
<input data-mcap type="text" id="mcap" name="lastname" placeholder="Market Cap">
</div>
</div>
</div>

如果我正确理解您要查找的是从输入字段A&B并将其求解为值C?下面我会给你一些类似的东西,让你看看,玩一玩,并利用这些知识来创造你想要的东西。

HTML:

<!-- field A -->
<input type="number" id="ctp" placeholder="Coin/Token Price" />
<!-- field B -->
<input type="number" id="cs" placeholder="Circulating Supply" />
<!-- field C, after entering value A & B we will have our answer here -->
<input type="number" id="mcap" placeholder="Market Cap" disabled />

我的示例将使用JQuery来处理JS部分。

$(document).ready(function(){
//below we create variable names for element selection
var cpt = document.querySelector('#ctp');
var cs = document.querySelector('#cs');
var mcap = document.querySelector('#mcap');
/*then we have 3 variables that will hold value A, B & C
var a = 0, b = 0, c = 0;
/*then we'll have an event listener that captures data when user input 
values in the first 2 fields*/
$(cpt).on('keydown',function(){
/*this means that when a key is pressed inside the first field we take 
whatever value is entered */
a = $(this).val();
//below we run a function that tests if both fields now have values
testFields();
});
/*below we have an event listener just like the one above for value B
$(cs).on('keydown',function(){
/*this means that when a key is pressed inside the second field we take 
whatever value is entered */
b = $(this).val();
//below we run a function that tests if both fields now have values
testFields();
});
/*the function that tests if value A and B are provided are are higher 
than 0 or not containing whitespaces, if both these conditions are true, we 
calculate and return value C 
, if not we wait for the user to input usable values*/
function testFields(){
if((a > 0 && b > 0) || (a !== '' && b !== '')){
/*if value a and b are greater than 0, we calculate c, else we do 
nothing*/
c = a * b;
/*once we have the value for C, we use the element selector 
variable to display the value to the 3rd input field*/
$(cmap).val(c);
}else{
/*if one or both values are less than 0 or blank we do nothing*/
return false;
}
}
});

这是一个总结。我们有3个输入字段,前2个接受数值,最后一个是只读字段,这意味着用户将无法在那里输入任何内容。然后我们创建可以用来从输入字段A&B并设置输入C的值。我们等待用户在字段A&B,我们测试插入的值是否大于0或不是空值,如果这两个条件都成立,我们继续并自动进行计算。

这可能不是你所期望的,而且肯定是一种更复杂的方法,但由于你是新手,愿意学习,这将是一个很好的例子和锻炼。从中,你可以完全理解预期,然后从中吸取教训。也许你甚至可以找到一种更好、更短的方式。

如果你有任何后续问题,请告诉我。祝你的项目一切顺利。

最新更新