简体   繁体   English

JavaScript输入文本框加号

[英]JavaScript input text box adding plus number

I have a question regarding the add sign in JavaScript I'm a bit confused on this. 我对JavaScript中的加号有疑问,对此我有些困惑。 I have this input text box which I will be input as 50 and it will add plus 50 . 我有这个输入文本框,我将输入50,它将加上50。 My result in adding the numbers which for example I input 50 the result is 5050 which is totally wrong. 我的结果相加,例如输入50,结果是5050,这是完全错误的。 Can someone help me on this? 有人可以帮我吗?

<!DOCTYPE html>
<html>
<head>
<title>activity 2</title>
<script type="text/javascript">
  function computeSalary(){
    var salaryData = document.form1.salary.value;
    var salary1 = salaryData  + 50;
    document.form1.newSalary.value = salary1;
  }
</script>
</head>
<body>
  <form name="form1">
    Enter the daily salary:
    <input type="text" name="salary" /><br />
    <input type="button" value="Compute" onClick="computeSalary();" /><br />
    <br />
    The new salary: <input type="text" name="newSalary" />
  </form>
</body>
</html>

Change the following line: 更改以下行:

var salary1 = parseInt(salaryData)  + 50; // Use parseInt or parseFloat

The reason is that JavaScript will coerce strings and integers into strings. 原因是JavaScript会将字符串和整数强制转换为字符串。 So your integer 50 is converted to a string and then concatenated. 因此,您的整数50将转换为字符串,然后进行连接。

You can convert the string value you're getting, which is being concatenated to your value, to a number by simply adding a plus sign: 您可以通过简单地添加加号将获取的字符串值(连接到您的值)转换为数字:

var salary1 = +salaryData  + 50;

jsFiddle example jsFiddle示例

You have to convert the value you got from the input control to float or integer before adding it using the + operator. 您必须先使用输入运算符将从输入控件中获得的值转换为浮点数或整数,然后再使用+运算符将其添加。 The + operator will convert both operands to a same type before adding both operands. +运算符会将两个操作数转换为相同类型,然后再添加两个操作数。 This is the primary reason why you got 5050 because the 50 of type int got converted to string. 这是您获得5050的主要原因,因为int类型的50已转换为字符串。

use this code: 使用此代码:

function computeSalary(){
    var salaryData = document.form1.salary.value;
    var salary1 = parseFloat(salaryData)  + 50;
    document.form1.newSalary.value = salary1;
}

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

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