-1

I want to make a calculater type form which gives addition of entered number without submit of form currently i made this code '

<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
 function myFunction() {
    var y = document.getElementById("txt1").value;
    var z = document.getElementById("txt2").value;
    var x = +y + +z;
    document.getElementById("demo").innerHTML = x;
  }
  window.onload =myFunction() ;
</script>

thanks in advance pls help me ...'

  • what is your back end language? java web application.. ? – Nomesh DeSilva Oct 04 '15 at 03:32
  • 2
    @NomeshDeSilva why is the back end language relevant to a client-side question? – NewToJS Oct 04 '15 at 03:39
  • http://stackoverflow.com/questions/4227043/how-do-i-cancel-form-submission-in-submit-button-onclick-event Simply return false from your function. There are various improvements to your code that can be made but that solves the form submission question. – Dan Belden Oct 04 '15 at 06:03

2 Answers2

0

I suppose what you here want to do is when you change any of the value of Textbox, answer should be displayed. Try using Jquery for this. hint: use .keypress() https://api.jquery.com/keypress/

khushali9
  • 1
  • 1
0

First you will want to attach event listeners to the input. I have done that in a function triggered from window.onload by targeting a class name calc. You also want to parseFloat the values.

This is to give you a starting point and show how to trigger the function without having to submit/click.

function myFunction() {
var y = parseFloat(document.getElementById("txt1").value);
var z = parseFloat(document.getElementById("txt2").value);
var x = y+z;
// If x = NaN empty variable x
if(isNaN(parseFloat(x))){x='';}
document.getElementById("demo").innerHTML = x;
}
window.onload=function(){
var inputs=document.getElementsByClassName('calc');
  for(var i=0; i<inputs.length; i++){
    // Listen for input > Call MyFunction
   inputs[i].addEventListener('input',myFunction,false);
  }
};
Enter first number:<input type="text" class="calc" id="txt1" name="text1">
Enter second number:<input type="text" class="calc" id="txt2" name="text2">
<p id="demo"></p>

If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

NewToJS
  • 2,762
  • 3
  • 14
  • 22