March 27, 201511 yr I store the users data in a variable via a form. I then perform calculation and print back to the screen. How do I get this to print back without page reload? <input type="text" id="inpt"> <input type="submit" value="Calculate" id="submit" onclick="calculate()"> <script> function calculate() { var input = document.getElementById("inpt").value; var rate = 10; var result = input * rate document.write(result); } </script>
March 27, 201511 yr First of all: don't use inline JavaScript such as your click handler, that should live within your calculate function. Secondly once you're done put the script in a external file. Finally NEVER use document.write it's gonna write over the whole page. you need to select a DOM element and put the result on that element. Here's a refactored version for you. <input type="text" id="inpt"> <input type="submit" value="Calculate" id="submit"> <div id="result"></div> (function(){ function calculate() { var input = document.getElementById("inpt").value, resultEl = document.getElementById("result"), rate = 10, result = input * rate; // check if the value is not a number if (isNaN(result)) { resultEl.innerHTML = "Please enter a number"; // exit the function return false; } // put the result inside the div. resultEl.innerHTML = result; } // store btn in a variable var btn = document.getElementById('submit'); // add click handler to btn that calls the calculate function. btn.addEventListener('click', calculate); }()); Fiddle http://jsfiddle.net/LpLa4goa/ Edited March 27, 201511 yr by rbrtsmith
March 27, 201511 yr Either that^ or alternatively create the result element with js: The createElement() method creates a new dom element and you can attach the string data to it with appendChild() https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
March 27, 201511 yr Either that^ or alternatively create the result element with js: The createElement() method creates a new dom element and you can attach the string data to it with appendChild() https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement This could be a better approach actually if you don't want that element polluting your HTML
Create an account or sign in to comment