hai,
Its very urgent.can somebody tell m,how to add two textboxes and then display the result in the third textbox ,using keypress -in javascript....
regards....

Dani AI

Generated

Nice start by — using an event + numeric conversion is exactly the right idea. One important clarification: onchange only fires when the control loses focus (or Enter is pressed). For live updates as the user types, prefer the input event (or keyup for very old browsers). Also avoid treating field values as strings (which concatenates) by converting or using numeric APIs.

Example (keeps the fields numeric, updates immediately):

<input id="n1" type="number" step="any" inputmode="decimal">
<input id="n2" type="number" step="any" inputmode="decimal">
<input id="sum" readonly>

<script>
const a = document.getElementById('n1');
const b = document.getElementById('n2');
const out = document.getElementById('sum');

const update = () => {
  const v1 = Number.isFinite(a.valueAsNumber) ? a.valueAsNumber : 0;
  const v2 = Number.isFinite(b.valueAsNumber) ? b.valueAsNumber : 0;
  out.value = (v1 + v2).toString();
};

a.addEventListener('input', update);
b.addEventListener('input', update);
update();
</script>

Notes and quick troubleshooting:

  • If you use plain text inputs, parse with parseFloat() (or parseInt(s, 10) for integers) and check isNaN() before adding.
  • valueAsNumber is handy with <input type="number"> because the browser parses for you; it yields NaN for invalid/empty values, so use a fallback (as shown).
  • Avoid keypress for updates — it doesn’t fire for paste/autofill and is inconsistent across keys. input handles typing, paste, drag, autocomplete.
  • If you need formatted results (2 decimals), use .toFixed(2) when assigning output. For international decimal separators or thousands formatting, format with Number.toLocaleString().

These points fill the gaps from the earlier posts: live updates, safe numeric parsing, and handling empty/invalid inputs.

i got solved...
using "onchange"
var1=document.getelementbyid('txt1').value
var2=document.getelementbyid('txt2').value
var3=Number(var1)+Number(var2)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.