繁体   English   中英

输入字段添加的javascript

[英]javascript on input field addition

 //// JavaScript function to add input values display into another input field function calculate() { var x = document.getElementById('fee_selector_holder').value; var y = document.getElementById('content').value; var result = document.getElementById('result'); var myResult = x + y; result.value = myResult; } 
 <input type="text" name="hostelfees" id="content" oninput="calculate()"> <input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()"> <input type="text" id="result" name="totalfee"> 

我给输入字段赋值,它添加连接但不添加请验证输入功能是正确还是错误一旦验证然后回复我这就是我的问题。

你有字符串,这就是连接的原因。 使用以下内容制作整数: http//www.w3schools.com/jsref/jsref_parseint.asp

它会运作良好。

首先,当您从DOM读取值时,它们将被读取为字符串。 您将不得不使用parseIntparseFloat将字符串转换为整数。

其次, +运算符有一个覆盖函数,用于字符串作为连接运算符。

另请注意,我使用了.value || 0 .value || 0 这里如果value不存在,对它执行算术运算将返回NaN因此添加默认值(0)。

 //// JavaScript function to add input values display into another input field function calculate() { var x = document.getElementById('fee_selector_holder').value || 0; var y = document.getElementById('content').value || 0; var result = document.getElementById('result'); var myResult = parseInt(x) + parseInt(y); result.value = myResult; } 
 <input type="text" name="hostelfees" id="content" oninput="calculate()"> <input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()"> <input type="text" id="result" name="totalfee"> 

您必须将输入值解析为整数,因为默认情况下所有输入值都是字符串:

 //// JavaScript function to add input values display into another input field function calculate() { var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank var y = document.getElementById('content').value || 0; // default value 0 if input is blank var result = document.getElementById('result'); var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here result.value = myResult; } 
 <input type="text" name="hostelfees" id="content" oninput="calculate()"> <input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()"> <input type="text" id="result" name="totalfee"> 

您应该向result添加属性

result.setAttribute("value", myResult);

暂无
暂无

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

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