0

My below code is working fine, but I want to know, is there any short method of doing same work only by JavaScript?

<lable for="fstValue"></lable> First number is: <input type="text" id="fstValue" value="" />
<lable for="sndValue"></lable> Second number is: <input type="text" id="sndValue" value="" />
<hr>
<div id="showResult1"></div>
<div id="showResult2"></div>
<div id="showResult3"></div>
<div id="showResult4"></div>

<button onclick="sandeep()">Check Result</button>

// Get the value, calculate and show the value

function sandeep(){

// Define local function - sandeep varriable
var a, b, resPlus, resMinus, resMultiple, resDivide;

// Get First & Second value
a = parseInt(document.getElementById("fstValue").value);
b = parseInt(document.getElementById("sndValue").value);

// Do calculation
resPlus = a + b;
resMinus = a - b;
resMultiple = a * b;
resDivide = a % b;

// Show result        
document.getElementById("showResult1").innerHTML="Plus is " + resPlus;

document.getElementById("showResult2").innerHTML="Minus is " + resMinus;

document.getElementById("showResult3").innerHTML="Multiple is " + resMultiple;

document.getElementById("showResult4").innerHTML="Divide is " + resDivide;

}
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
Sandy
  • 255
  • 1
  • 7
  • 16

2 Answers2

1

Can certainly array-drive this. Note my sue of parseInt(*, 10), this is important.

var a = parseInt(document.getElementById("fstValue").value, 10);
var b = parseInt(document.getElementById("sndValue").value, 10);

var texts = ["Plus", "Minus", "Multiple", "Divide"];
var results = [a + b, a - b, a * b, a / b];

for(var i = 0; i < 4; i++ ) {
    document.getElementById("showResult" + (i+1) + ").innerHTML=" texts[i] + " is " + results[i];
}

Note you're discovering the problem that frameworks like Angular.js and everything else are attempting to solve. Note the following is pseudo code. It sure would be better if you had a snippet of HTML template

<p>{text} is {result}</p>

And you could put this in a loop

{{iterate over results object}}
    <p>{result.text} is {result.results}</p>
{{ end iterate}}

Now far less work has to happen in Javascript. But more importantly, work that should happen in HTML now happens in HTML (data layout), and what happens in JS should happen in JS (getting data). That's the state-of-the-art theory.

djechlin
  • 54,898
  • 29
  • 144
  • 264
0

You can make your own functions at least:

function getElement(id)
{
    return document.getElementById(id);
}

And now you can use just getElement("showResult1");

Also you can do the same for innerHtml and other stuff that you repeat in your code.

Karmidzhanov
  • 199
  • 2
  • 14