Display result of computation (javascript) in HTML - javascript

I am trying to take two numbers from html and using javascript return sum of both but my num1 and num2 contains HTMLInputElement??
html:
<head>
<script type ="text/javascript" src="functions.js"></script>
</head>
<body>
Value 1: <input type="text" id="tb1" name="tb1"><br/>
Value 2: <input type="text" id="tb2" name="tb2"><br/>
Result: <input type="text" id="tb3" name="tb3"><br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
</body>
javascript:
function validateForm() {
var x = document.getElementById("tb1");
var y = document.getElementById("tb2");
if (x == null || x == "" || y == null || y == "")
{
alert("Value cannot be empty");
return false;
}
else {
//myAdd(x,y);
alert(x + y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").innerHTML = total;
}
}

You are not parsing and adding values from those two inputs, but objects itself. Because of that your if statement block would never run, as you are comparing object to null.Also and you can't set innerHTML of an input,have to use .value.Check the snippet below
parseFloat(x) //you must parseFloat(x.value),
document.getElementById("tb3").value = total; //you have to use .value instead of .innerHTML with input
function validateForm() {
var x = document.getElementById("tb1").value;
var y = document.getElementById("tb2").value;
if (x == null || x === "" || y == null || y === "") {
alert("Value cannot be empty");
return false;
} else {
//myAdd(x,y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").value = total;
}
}
Value 1:
<input type="text" id="tb1" name="tb1">
<br/>Value 2:
<input type="text" id="tb2" name="tb2">
<br/>Result:
<input type="text" id="tb3" name="tb3">
<br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>

Related

I started learning JavaScript and I have a problem with if statement

I started learning JavaScript and I want to do my own small project 'BMI calculator' but I can't find an error with my if statement.
Everything working fine but if as a input I will type for example 0, I don't see any warning message instead I see result of calculation.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input id="height">
<br> Weight: <input id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
Because you don't stop the function when you detect invalid input. You put the error message into the message panel, but then you continue to the code that performs the calculation with the invalid input.
You should return from the function after displaying the error message.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
return;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
return;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input type="number" id="height">
<br> Weight: <input type="number" id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>

How to show message instead of alert in javascript calculator as follows:

I want to calculate values of x and y from textbox values and the values
should not be empty and not alphabetic. I have been able to do all these
so far. However i do not want the result to be in a pop up. I want the
result to be displayed as a text just under the buttons and it says 'Your
result is.. '.
I have seen on the net that they use document.getElementById but I
don't know how to use it.
<html>
<form>
1st Number : <input type="text" id="num1" /><br>
2nd Number: <input type="text" id="num2" /><br><br>
<button onclick="add(num1.value,num2.value)">Addition</button>
<script>
function add(x,y) {
if(x.length == 0 || y.length == 0){
alert("Numbers cannot be blank");
return;
}
if(isNaN(x) || isNaN(y)){
alert("Value entered is not numeric");
return;
}
var result = parseInt(x) + parseInt(y);
alert("Addition: " + result);
}
</script>
</body>
</html>
I want the result to be displayed as a text just under the buttons and it
says 'Your result is.. '
Please send me the codes if you are able to do it.
Simply create a div element after your button:
<div id="result"></div>
And update it with the sum result by replacing your alert code:
var result = parseInt(x, 10) + parseInt(y, 10);
document.getElementById('result').innerHTML = 'Your result is ' + result;
<body>
<div>1st Number : <input type="text" id="num1" /></div>
<div>2nd Number: <input type="text" id="num2" /></div>
<button onclick="add()">Addition</button>
<div id='result'></div>
<script>
function add() {
let x = document.getElementById('num1').value;
let y = document.getElementById('num2').value;
if(x.length == 0 || y.length == 0){
alert("Numbers cannot be blank");
document.getElementById('result').innerText = '';
return;
}
else if(isNaN(x) || isNaN(y)){
alert("Value entered is not numeric");
}
var result = Number(x) + Number(y);
document.getElementById('result').innerText = "Your result is: " + result;
}
</script>
</body>

basic calculator created in javascript.. use an alert to tell user about any errors. the possible errors include:

I've created a basic 4 function calculator in JavaScript and now I need to use an alert to tell the user about any errors. the possible errors are:
One or both input fields are blank
One or both input fields < -9999 or greater than 9999
Divide by zero
Illegal character in either input field. Only 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, and – are allowed.
Code:
function multiplyBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 / num2;
}
function additionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 + num2;
}
function subtractionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 - num2;
}
body {
margin: 30px;
}
<!DOCTYPE html>
<html>
<head>
<body>
<form>
1st Number : <input type="text" id="firstNumber"> 2nd Number: <input type="text" id="secondNumber"> The Result is :
<span id="result"></span>
<br>
</br>
<br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
<input type="button" onClick="additionBy()" Value="Add" />
<input type="button" onClick="subtractionBy()" Value="Sub" />
</br>
</form>
<script type="text/javascript" src="fourth.js">
</script>
</body>
</html>
first of all define the input tag type as number like below
1st Number : <input type="number" id="firstNumber" >
2nd Number: <input type="number" id="secondNumber" >
so, in that case user will not be able to enter invalid input.
secondly, check the divide by zero condition into the function only
There are libraries for validation that you can get but lets start simple. Rework what you have to remove duplicated code and then add functions to do your validation.
This is JUST A START not a complete solution, you have to do work. I will leave it to you to add the OTHER validation you need, but you can see how this is doing it with the couple I added.
function showResults(results) {
document.getElementById("result").innerHTML = results;
}
function multiplyBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 * num2);
}
function divideBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 / num2);
}
function additionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 + num2);
}
function subtractionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 - num2);
}
function actionClicker() {
let number1 = document.getElementById("firstNumber");
let number2 = document.getElementById("secondNumber");
validateNumber(number1);
validateNumber(number2);
var attribute = this.getAttribute("data-myattribute");
var expr = attribute;
switch (expr) {
case 'multiply':
multiplyBy(number1, number2);
break;
case 'division':
divideBy(number1, number2);
break;
case 'subtract':
subtractionBy(number1, number2);
break;
case 'addition':
additionBy(number1, number2);
break;
default:
console.log('Sorry, we do not find ' + expr + '.');
}
}
function showValidationMessage(message) {
alert(message);
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isEmpty(n) {
return n === "";
}
function isInRange(n) {
if (isNumeric(n) && !isEmpty(n)) {
num = parseInt(n, 10);
return num >= -9999 && num <= 9999;
}
return false;
}
function validateNumber(el) {
let hasError = false;
el.classList.remove("has-error");
// add your validation
let message = "get stuff better";
if (!isNumeric(el.value)) {
message = "Not a number.";
hasError = true;
}
if (isEmpty(el.value)) {
message = "Not a number, cannot be empty.";
hasError = true;
}
if (hasError) {
el.classList.add("has-error");
showValidationMessage(message);
}
}
function modifyNumbers(event) {
let el = event.target;
validateNumber(el);
}
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var buttons = document.getElementsByClassName('actions');
// add event listener to buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', actionClicker, false);
}
num1.addEventListener("change", modifyNumbers, false);
num2.addEventListener("change", modifyNumbers, false);
body {
margin: 30px;
}
.buttons {
margin: 2em;
}
label {
padding-right: 1em;
padding-left: 1em
}
.has-error {
background-color: lightpink;
border: solid red 1px;
}
.numbers {
width: 11em;
}
<body>
<form>
<label for="firstNumber">1st Number:</label><input class="numbers" type="number" id="firstNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span><label for="secondNumber">2nd Number:</label><input class="numbers"
type="number" id="secondNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span>
<div><label>The Result is:</label>
<div id="result"></div>
</div>
<div class="buttons">
<button type="button" class="actions" id="multiply" data-myattribute="multiply">Multiply</button>
<button type="button" class="actions" id="divide" data-myattribute="division">Divide</button>
<button type="button" class="actions" id="add" data-myattribute="addition">Add</button>
<button type="button" class="actions" id="subtract" data-myattribute="subtract">Sub</button>
</div>
</form>
</body>
What you are looking for is a validation pattern.
To check if the inputs are valid you can perform checks at the beginning of your math functions. For example
var $num1 = document.getElementById("firstNumber");
var $num2 = document.getElementById("secondNumber");
var $result = document.getElementById("result");
function checkValid(division){
var num1 = $num1.value;
var num2 = $num2.value;
if(num1 == null || num1 > 9999 || num1 < -9999){
return false;
}
if(num2 == null || num2 > 9999 || num2 < -9999){
return false;
}
if(division && num2 === 0){
return false
}
}
function multiplyBy() {
if(check()){
num1 = $num1.value;
num2 = $num2.value;
$result.innerHTML = num1 * num2;
} else {
alert('some error message');
}
}
then in your division function call check(true)
This is just one way to handle it. You could call alert in the check function before returning or even return your error messages from the check function. This should get going in the right direction.
Also I do recommend the <input type="number"> changes by Hasan as well.

Increasing the label value by one on button click using javascript

I have three labels with a button and on but click i need to increment the value by 1
<script>
function incrementValue() {
var label = document.getElementById('number');
label.textContent = (parseInt(label.textContent, 10) || 0) + 1;
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table >
<tr><td><asp:Label ID="lbl1" runat="server" Text="Major"></asp:Label></td><td></td></tr>
<tr><td><asp:Label ID="lbl2" runat="server" Text="1.0"></asp:Label></td><td></td></tr>
<tr><td><asp:Label ID="number" runat="server" Text="0"></asp:Label></td><td></td></tr>
</table>
<input type="button" onclick="incrementValue()" value="click" />
</div>
Use textContent to get and update the text content inside label. Then get last digit using match(), increment and update the content.
<script>
function incrementValue() {
var value = parseInt(document.getElementById('number').textContent.match(/\d+$/)[0], 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').textContent = 'major 1.0 ' + value;
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
It can be more simplified
<script>
function incrementValue() {
var label = document.getElementById('number');
label.textContent = 'major 1.0 ' + ((parseInt(label.textContent.match(/\d+$/)[0], 10) || 0) + 1);
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
In case the string varies then, you can do something like this
<script>
function incrementValue() {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*)(\d+)$/);
label.textContent = m[1] + ((parseInt(m[2], 10) || 0) + 1);
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
With your own simple ternary operator
<script>
function incrementValue() {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*?)(\d+)$/);
var value = parseInt(m[2], 10);
value = isNaN(value) ? 0 : value;
label.textContent = m[1] + (value + 1)
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
UPDATE : As per the updated question you can do
<script>
document.onkeyup = KeyCheck;
function KeyCheck(e) {
var key = (window.event) ? event.keyCode : e.keyCode;
if (key == 113) {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*?)(\d+)$/);
var value = parseInt(m[2], 10);
value = isNaN(value) ? 0 : value;
label.textContent = m[1] + (value + 1)
}
}
</script>
<label id="number">major 1.0 0</label>

Javascript onkeydown function runs and then display goes away

first time on the website, anyway my problem is that when I use onkeydown and then use GetChar to check if the enter key was pressed, when operAtion runs,the results of the function only shows on the screen for about a second and then goes away, if the user uses the onclick (clicks the enter button), then this problem doesnt occur. How do I get the result of operAtion to stay on the screen when onkeydown is used. The website is sqrtcalc.comze.com if you want to see what I mean
sqrtcalc
<!DOCTYPE html>
<html>
<head>
<title>Square Root Calculator</title>
<script language="javascript">
function operAtion (form){
var x = form.inputbox.value;
if (isNaN(x)){
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0){
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == ""){
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1/2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
}
function GetChar (event,form){
var keyCode = event.keyCode;
if (keyCode == 13){
operAtion(form);
}
}
</script>
<p></p>
</head>
<body>
<form name="myform" action="" method="get" style = "font-size:50px"><strong>Square Root Calculator</strong></br>
</br>
<input type="text" name="inputbox" value = "" onkeydown = "GetChar(event,this.form);"> </br>
</br>
<input id="button" type="button" name="button" value=" Enter " onclick="operAtion(this.form)" >
</form>
<h1 id = "failsafe"></h1>
</br>
</br>
</br>
<h1 id = "demo"></h1>
</br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>
<img border="0" src="http://counter.rapidcounter.com/counter/1353157574/a"; ALIGN="middle" HSPACE="4" VSPACE="2" style = "padding-left:1400px;">
</body>
</html>
Add this code:
window.onload = function(){
document.getElementById("myform").onsubmit = function(){
return false;
}
}
And add the id attribute id="myform" to the <form> tag.
I refactored your code a little:
I removed your inline functions (inline JS isn't exactly best
practice)
I added an ID to your form so it could be referenced
I added return false; to keep the form from submitting
onsubmit handles both click and enter
Javascript
document.getElementById('myform').onsubmit = function() {
var x = this.inputbox.value;
if (isNaN(x)) {
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0) {
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == "") {
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1 / 2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
return false;
}​
HTML
<form name="myform" action="" method="get" style="font-size:50px" id="myform"><strong>Square Root Calculator</strong><br>
<br>
<input type="text" name="inputbox"> <br>
<br>
<input id="button" type="submit" name="button" value=" Enter ">
</form>
<h1 id="failsafe"></h1>
<h1 id="demo"></h1>
Working demo​

Categories