I have three labels. I want to subtract two labels and put the result in the third label.
$(document).ready(function() {
//Get the texts from both textboxes
var txt1 = document.getElementById("addition").value;
var txt2 = document.getElementById("investplan").value;
//Substract that
var res = parseInt(txt1) - parseInt(txt2);
//Set the value to your div
document.getElementById("subtraction").innerHtml = res;
});
<label id="investplan">23940</label>
<label id="addition">138790</label>
<label id="subtraction"></label>
A few pointers:
You are mixing up jQuery and pure javascript. $(document).ready()
is jQuery - you must include the jQuery library. I substituted the pure JS equivalent. ALSO .val()
is how you read a value in jQuery (which is what you may have been thinking with .value
), whereas in pure JS you probably want .innerText
or .textContent
or .innerHTML
It is .innerHTML
not .innerHtml
Use Divs or Spans instead of label tag. The label tag is intended to group a clickable control (eg a radio button) with some additional text, so that clicking on the text fires the radio button control.
document.addEventListener('DOMContentLoaded',() => {
//Get the texts from both textboxes
var txt1 = document.getElementById("addition").innerText;
var txt2 = document.getElementById("investplan").innerText;
console.log(txt1);
//Substract that
var res = parseInt(txt1) - parseInt(txt2);
console.log(res);
//Set the value to your div
document.getElementById("subtraction").innerHTML = res;
});
<label id="investplan">23940</label>
<label id="addition">138790</label>
<label id="subtraction"></label>
Reference:
https://www.javascripttutorial.net/javascript-dom/javascript-page-load-events/