[英]How to print the values in the same input text field using JS
I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box.我使用 HTML 创建了 5 个输入文本框,并在单击按钮时制作了一个按钮,值将打印结果输入文本框。 The first 4 fields are my inputs and the last text field is my output.
前 4 个字段是我的输入,最后一个文本字段是我的输出。 unable to debug the issue.
无法调试问题。 kindly find the code and help to find the issue.
请找到代码并帮助找到问题。
function JS(){ var h=document.getElementById('h').value; var w=document.getElementById('w').value; var g=document.getElementById('g').value; var t=document.getElementById('t').value; var total =(h+w+g+t); document.getElementById('result').innerHTML=total; }
<h2> Calculator</h2> <input type="text" placeholder="value1" id="h"> <input type="text" placeholder="value2"id="w"> <input type="text" placeholder="value3" id="g"> <input type="text" placeholder="value4" id="t"> <input type="text" placeholder="result" id="result"> <!-- <p id="result"> </p> --> <button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value
instead of .innerHTML
.value
而不是.innerHTML
There are two keys to resolving your issue:解决您的问题有两个关键:
+
in front of the value assignments.+
来实现这一点。 If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.value
of the input element, not the innerHTML
.value
,而不是innerHTML
。 If you'd rather use a <p>
element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText
.<p>
元素,您似乎在示例代码中注释掉了它(并且为了我的答案的完整性而恢复了它),请考虑使用innerText
。 See example here:请参阅此处的示例:
function JS() { var h = +document.getElementById('h').value; var w = +document.getElementById('w').value; var g = +document.getElementById('g').value; var t = +document.getElementById('t').value; let p_result = document.getElementById('p_result'); var total = (h + w + g + t); document.getElementById('result').value = total; p_result.innerText = total; }
<h2> Calculator</h2> <input type="text" placeholder="value1" id="h"> <input type="text" placeholder="value2" id="w"> <input type="text" placeholder="value3" id="g"> <input type="text" placeholder="value4" id="t"> <input type="text" placeholder="result" id="result"> <br> <p id="p_result" style="color:red;"></p> <br> <button id="btn" onClick="JS()">Calculate</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.