简体   繁体   中英

Linking html <input> and <output> with JavaScript function

So I have this code which basically does a simple math function but now I do not know how to link the <input> and the <output> tags with the JavaScript so that when users put a digit in <input> the script is run and the result is displayed in the <output> Any help is appreciated and please be helpful as I am still learning.

 function computation(number) { let newNumber = number + (1/100 * number) + 1000; let roundedNumber = Math.round(newNumber/100)*100; return roundedNumber; } 
 <p>Enter Amount Here:</p> <input type="text" name="value"></input> <button class="button" onClick="computation()">Calculate!</button> <p>Final Amount</p> <div class="output"> <output for="roundedNumber" name="finalAmount"></output> </div> 

First thing you are having number as a parameter to function but function is not getting it when you call it.So you can use

document.getElementById('id').value 

to get the value. Have a look at this.

 function computation() { let number = document.getElementById('input1').value; let newNumber = number + (1/100 * number) + 1000; let roundedNumber = Math.round(newNumber/100) * 100; document.getElementById('output1').innerHTML = roundedNumber; } 
 <p>Enter Amount Here:</p><br> <input type="text" name="value1" id="input1"> <button class="button" onClick="computation()">Calculate!</button> <p>Final Amount</p> <div class="output"> <output for="roundedNumber" name="finalAmount" id="output1"></output> </div> 

Follow below simple steps. 1) Add ids to your input and output tags, just put same as name

<input type="text" name="value" id="value" />
<output for="roundedNumber" name="finalAmount" id="finalAmount"/>

2) use js document.getElementById("inputid").value

let num = document.getElementById("value").value

3) use the same way to set value. lets assume u want to show it in paragraph tag.

<p id="output"></p>
document.getElementById("output").innerHTML =newNum;

4) for active tags use .value instant of .innerHTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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