I'm writing a function to calculate the sum, product, and see which number is greater. I have the sum and product, but when I try to compare the 2 numbers, it won't work. I'm trying to get all 3 items (sum, product, and comparison) to show when the button is clicked. Here is the code:
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
<!-- Function -->
<script>
function calculate() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var sum = parseInt(x) + parseInt(y);
var product = parseInt(x) * parseInt(y);
document.querySelector("#result").innerHTML = ("The sum is " +
sum + " and the product is " + product);
}
</script>
<!-- This was the if statement that won't work. I was placing this in the same function right after the 1st querySelector.
if (x > y) {
document.querySelector("#result").innerHTML = (x + " is greater than " + y);
} else {
document.querySelector("#result").innerHTML = (y + " is greater than " + x);
}
-->
I moved the cast of x and y into integers to the assignment of that variables. Afterwards you can just use them as integers without worrying.
function calculate() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var sum = x + y;
var product = x * y;
document.querySelector("#result").innerHTML = ("The sum is " +
sum + " and the product is " + product + ". ");
if (x > y) {
document.querySelector("#result").innerHTML += (x + " is greater than " + y);
// TODO: what about x == y ?
} else {
document.querySelector("#result").innerHTML += (y + " is greater than " + x);
}
}
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
Don't parse the numbers several times. Parse them once and then use the parsed values.
Similarly, don't use querySelector to get the same element several times, use it once and save it into a variable that you can use later.
And since you're getting the element by ID, then it is better to use getElelementByID() instead of querySelector().
function calculate() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
x = parseInt(x);
y = parseInt(y);
var sum = x + y;
var product = x * y;
var result = document.querySelector("#result");
result.innerHTML = "The sum is " + sum + " and the product is " + product + "<br/>";
if (x > y) {
result.innerHTML += x + " is greater than " + y;
} else {
result.innerHTML += y + " is greater than " + x;
}
}
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
Basically your Problem is that in your code you are overwriting your div element twice.for ex Your div element result for:
```
if (x > y) {
document.querySelector("#result").innerHTML = (x + " is greater than " + y);
} else {
document.querySelector("#result").innerHTML = (y + " is greater than " + x);
}
```
is replaced by immediate following value:
```
document.querySelector("#result").innerHTML = ("The sum is " +sum + " and the product is " + product);
```
I suggest you to either concatenate both innerHTML values or make a seperate div element for either of them.
Hope this will help you.
Related
This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80
It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>
function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var output = "";
var output2 = "";
function isEven(split_string) {
if (split_string.length % 2 == 0)
return output;
else
return output2;
}
for (var i = 0; i < split_string.length; i += 2) {
output += " " + split_string[i + 1] + " " + split_string[i];
document.getElementById("reverse").innerHTML = output;
}
output2 += " " + output + " " + split_string[split_string.length - 1];
document.getElementById("reverse").innerHTML = output2;
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
Output shown: undefined + string.
How can i remove this?
I like it if input is 1 2 3 4 then o/t is 2 1 4 3
and another condition is if string is odd
ex 1 2 3 4 5 then needed 2 1 4 3 5
Try this
for (var i = split_string.length-1; i >= 0; i --) {
output += " " + split_string[i ] + " ";
}
document.getElementById("reverse").innerHTML = output;
function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var output = "";
var output2 = "";
function isEven(split_string) {
if (split_string.length % 2 == 0)
return output;
else
return output2;
}
for (var i = split_string.length-1; i >= 0; i --) {
output += " " + split_string[i ] + " ";
}
document.getElementById("reverse").innerHTML = output;
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
That is because, you are splitting using " " and using split_string[i + 1].
If I enter "Hello World! Foo."
split_string will be like
0: Hello
1: World!
2: Foo.
First Iteration will work fine. Then you increment as i+=2, so now i is 2 and split_string[i + 1] will be split_string[3] i.e. undefined.
Same will happen if you do not enter value with any spaces.
You can try something like this:
function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var _temp = [];
var len = split_string.length;
console.log(len, split_string)
for(var i=0; i<len/2; i++){
_temp.push(split_string[(i*2) + 1]);
_temp.push(split_string[(i*2)]);
}
console.log(_temp);
document.getElementById("reverse").innerHTML = _temp.join(" ");
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
Try this simple method...
var str = "1234567";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (i == 0 || i % 2 === 0) {
var j =i+1;
if(typeof str[j] === "undefined"){
newstr = newstr + str[i];
}else{
newstr = newstr + str[i + 1] + str[i];
}
}
}
Hope this help you...
DEMO
ok, so I am trying to make a midpoint calculator in JavaScript for fun and to practice with the language, The formula is pretty simple, it is just x1 + x2 / 2 and y1 + y2 / 2, I want the user to be able to define the x and y coordinates, and this is what I have come up with:
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excelent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var comma = (",");
var exclam = ("!");
var two = (2)
var x1x2 = (x1 + x2 / two);
var y1y2 = (y2 + y2 / two );
alert(midText + x1x2 + comma + y1y2 + exclam);
for some reason, this is not calculating correctly and turning in wrong answers, go ahead and try it out. it may be some weird misstype from me, I am fairly new to javascript, only having worked with the language for an hour or two. any help would be very much appreciated! thanks in advance!
(x1 + x2 / two)
is dividing then concatenating a string and a number.
Try
((+x1 + +x2) / two)
which uses the prefix + operator to coerce strings to numbers and parenthesizes the low-precedence addition.
You can see this in action by doing
alert(("1" + "0") / 2) // alerts 5 since "1" + "0" == "10"
alert((1 + 0) / 2) // alerts 0.5 since 1 + 0 == 1
perhaps you need
var x1x2 = (parseInt(x1) + parseInt(x2)) / two;
var y1y2 = (parseInt(y2) + parseInt(y2)) / two;
Demo jsFiddle
JS
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excellent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var x1x2 = (+x1 + +x2) / 2;
var y1y2 = (+y2 + +y2) / 2 ;
alert(midText + x1x2 + "," + y1y2 + "!");
The way I would do it (jsFiddle)
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<form>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" />
</div>
<div>
<input type="submit" value="Calculate" onclick="Calculate()"/>
</div>
</form>
<div>
<span id="results"></span>
</div>
JS
function Calculate(){
event.preventDefault();
var x1 = parseFloat(document.getElementById('x1').value);
var y1 = parseFloat(document.getElementById('y1').value);
var x2 = parseFloat(document.getElementById('x2').value);
var y2 = parseFloat(document.getElementById('y2').value);
var x1x2 = parseFloat((x1 + +x2) / 2);
var y1y2 = parseFloat((+y2 + +y2) / 2);
document.getElementById("results").innerHTML=("your midpoints are: " + x1x2 + "," + y1y2 + "!");
}
Using KnockoutJS
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" data-bind="value: x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" data-bind="value: y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" data-bind="value: x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" data-bind="value: y2" />
</div>
<div>
your midpoints are: <span id="results" data-bind="text: Midpoint"></span>!
</div>
JS
var MidpointCalulatorViewModel = function () {
var self = this;
self.x1 = ko.observable();
self.x2 = ko.observable();
self.y1 = ko.observable();
self.y2 = ko.observable();
self.x1x2 = ko.computed(function () {
return parseFloat((parseFloat(self.x1()) + parseFloat(self.x2())) / 2);
}, self);
self.y1y2 = ko.computed(function () {
return parseFloat((parseFloat(self.y1()) + parseFloat(self.y2())) / 2);
}, self);
self.Midpoint = ko.computed(function () {
return self.x1x2() + "," + self.y1y2();
}, self);
};
ko.applyBindings(new MidpointCalulatorViewModel());
Note you need validation
This is the Html form I use.
<form name="calculate" method="get" action="#" onsubmit="return Validate()">
<label>Enter a number</label>
<input id="numb1" name="numb1" id="numb2" placeholder="Number 1">
<label>Enter another number</label>
<input id="numb2" name="numb2" id="numb2" placeholder="Number 2">
<label>Result</label>
<textarea style="text-align:center; height:85px; max-height:85px;" name="summ" id="summ" disabled="disabled" placeholder="Result" dir="ltr"></textarea>
<br />
<input id="calc" name="calc" type="submit" value="Calculate!">
The JS
function Validate() {
if (calculate.numb1.value == "" || calculate.numb2.value == "") {
alert("Check the form again");
calculate.numb1.focus();
document.getElementById('summ').value = "";
return (false);
}
Update()
return (true);
}
function Update() {
var plus = calculate.numb1.value + calculate.numb2.value;
var minus = calculate.numb1.value - calculate.numb2.value;
var mult = calculate.numb1.value * calculate.numb2.value;
var div = calculate.numb1.value / calculate.numb2.value;
var multi = document.getElementById("summ").value = calculate.numb1.value + "+" + calculate.numb2.value + "=" + plus + "\n" + calculate.numb1.value + "-" + calculate.numb2.value + "=" + minus + "\n" + calculate.numb1.value + "*" + calculate.numb2.value + "=" + mult + "\n" + calculate.numb1.value + "/" + calculate.numb2.value + "=" + div;
}
All the calculations work perfectly accept the Plus function.
When you type 4+4 for example you get 44...
I tried parseFloat, but still, nothing changes.
var numb1 = parseFloat(document.calculate.numb1.value);
var numb2 = parseFloat(document.calculate.numb2.value);
var plus = numb1 + numb2;
var minus = numb1 - numb2;
var mult = numb1 * numb2;
var div = numb1 / numb2;
Convert them to numbers first.
Do this with every calculation with a string value.
var plus = Number(calculate.numb1.value) + Number(calculate.numb2.value);
Léon