简体   繁体   English

使用JavaScript将百分比添加到输入字段中的值?

[英]adding percentage to a value in an input field using javascript?

I am trying to add a percentage to a value (number) that is in an input field. 我正在尝试向输入字段中的值(数字)添加一个百分比。

is this possible using javascript? 使用JavaScript可以吗?

this is what i came up with but it doesn't do anything. 这是我想出的,但没有做任何事情。

        <script language="javascript">
function multiply() {
    var ans = (document.form.myNumber.value) + ("3.5%"),

        total = Math.round(ans*100)/100;

    document.form.sum_total.value = total;
}

</script>

please let me know if this question is not suitable for this website and i will delete it. 如果这个问题不适合该网站,请告诉我,我将其删除。

Thanks 谢谢

EDIT: 编辑:

So far i have tried everything and nothing seem to work for me. 到目前为止,我已经尝试了一切,似乎没有任何工作对我有用。

here is what I have done so far: 到目前为止,这是我所做的:

JAVASCRIPT: JAVASCRIPT:

<script type="text/javascript">
$("#myNumber").keyup(function(){
    $("#sum_total").val($(this).val());
});


       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : event.keyCode;

          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;


          return true;
       }
</script>

<script language="javascript">
function multiply() {
var ans = parseFloat(document.form.sum_total.value);

ans = (ans * 0.035) + ans
}

</script>

HTML: HTML:

        <form>
<input type="text"id="myNumber" name="myNumber" value="" onkeyup="multiply()" onkeypress="return isNumberKey(event)" ><br  /><br  />
 <input type="text" id="sum_total" readonly="true" name="sum_total" value=""> 

 <input name="perc" id="perc" type="hidden" value="3.5%" />
 </form>

Basic math applies here. 基本数学在这里适用。 3.5% is actual 0.035, so parse you input value: 3.5%是实际的0.035,因此请解析您的输入值:

var ans = parseFloat(document.form.myNumber.value);

Do the math 算一算

ans = (ans * 0.035) + ans

Or multiply by 103.5% 或乘以103.5%

ans *= 1.035

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM