Basic Javascript: Cannot output result on html - javascript

I'm trying to learn Javascript by making a simple calculator, but somehow the result of the calculation doesn't show up. I'm wondering what's wrong with my code. I've tried many ways to understand the error, but I still don't know why. The calculation works just fine in the console, it's just the output that seems to have the problem.
Can somebody help me?
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").innerHtml = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>

innerHtml is invalid attribute, you need to use innerHTML instead like:
document.querySelector("#result").innerHTML = calculate;

You should be using textContent instead of innerHtml
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").textContent = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>

An "id" should be unique within a page and should not
be used more than once value1 and value2 in doesn't
recognise by documents.querySelector() so instead of
this use
Var a =
parseInt(document.getElementById("value1").value);
var b =
parseInt(document.getElementById("value2").value);

Related

HTML, how to get always +1 sum

I'm doing a point counter in general and I have no idea how to do it anymore, so I would like to add +1 to the sum on the "=" button and add it only once if someone could help me, I would be grateful
Code: https://pastebin.com/C26VFyev
var result = 0;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + 1);
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
Use a variable for what you add to the sum. Initialize it to 1 for the first time, than change it to 0 for future uses.
var result = 0;
var addition = 1;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + addition);
if (addition == 1) {
addition = 0;
}
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>

What am I missing in my JavaScript code?

I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>

Using forms to Collect data for Javascript functions?

I'm trying to collect data via forms on one page, then transfer that data to the next page for use in a JS function.
(Specifically, I want the user to input values for A, B, and C of the Quadratic equation, and then send to a page where a script takes those values and runs the equation + outputs an answer).
Here the code for my first page --->
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad" method="get" action="JS_B.html">
<input
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" method="get" action="JS_B.html" value="Submit">
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
</form>
Here is the code for my second page --->
<title>JS_Math Scripts</title>
<body>
<script type="Javascript">
function answer()
{
var a = a_val
document.writeln(a_val)
var b = b_val
var c = c_val
var root = Math.pow(b, 2) - 4 * a * c
var answer1 = (-b + Math.sqrt(root)) / 2*a
var answer2 = (-b - Math.sqrt(root)) / 2*a
if(root<'0');
{
alert('This equation has no real solution.')
}else{
if(root=='0')
{
answerOne = answer1
document.writeln(answerOne)
answerTwo = 'No Second Answer'
}else{
answerOne = answer1
document.writeln(answerOne)
answerTwo = answer2
document.writeln(answerTwo)
}
}
}
// End -->
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
So anyways, when I input values for A, B, and C it takes me to the second page, but I'm not getting a result. I've tried inspect element and the console isn't indicating any errors, so I think my data is transferring correctly. Any ideas?
You can use FormData() to retrieve values from <input> elements within <form>; use JSON.stringify(), encodeURIComponent() to pass values from form to JS_B.html as query string.
At window load event at JS_B.html, use decodeURIComponent(), JSON.parse() to retrieve object at location.search; destructuring assignment to set variables within answer function using passed object.
Include ; following variable assignments, remove ; following if condition
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Welcome to the Math Equation Solver </h1>
<p> Which equation would you like to solve? (Simply input the data for the equation you wish to solve). </p>
<form name="quad">
<input type="text" name="a_val" size="5">
<br>
<input type="text" name="b_val" size="5">
<br>
<input type="text" name="c_val" size="5">
<br>
<input type="submit" value="Submit">
<!--
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
-->
</form>
<script>
var form = document.querySelector("form");
form.onsubmit = function(e) {
e.preventDefault();
var data = new FormData(this);
var obj = {};
for (prop of data.entries()) {
obj[prop[0]] = prop[1]
};
var query = encodeURIComponent(JSON.stringify(obj));
location.href = "JS_B.html?" + query;
}
</script>
</body>
</html>
JS_B.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function answer(obj) {
var {
a_val: a,
b_val: b,
c_val: c
} = obj;
document.writeln(a);
var root = Math.pow(b, 2) - 4 * a * c;
var answer1 = (-b + Math.sqrt(root)) / 2 * a;
var answer2 = (-b - Math.sqrt(root)) / 2 * a;
if (root < 0) {
alert('This equation has no real solution.')
} else {
if (root == 0) {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = 'No Second Answer'
} else {
answerOne = answer1;
document.writeln(answerOne);
answerTwo = answer2;
document.writeln(answerTwo)
}
}
} // End -->
window.onload = function() {
var obj = JSON.parse(decodeURIComponent(location.search.slice(1)));
console.log(obj);
answer(obj);
}
</script>
<input type="hidden" name="a_val">
<input type="hidden" name="b_val">
<input type="hidden" name="c_val">
<input type="hidden" name="answerOne">
<input type="hidden" name="answerTwo">
<input type="hidden" name="Answer">
</body>
</html>
plnkr http://plnkr.co/edit/aaY5rcJ6v0g7bdEEr7h0?p=preview

Create an HTML form with one field and button

I'm new in coding , there is a question that someone gave me and I can't find the right answer , this is the question :
Create an HTML form with one field and button.On button click,get the input,and return the sum of the previous value and the current input value.The value is 0 and input is 5->output is 5,then value is 5,input is 6-> output is 11 and etc.
I tried few things nothing even close ,
if someone can give me the answer Ill be much appreciated , thanks.
There you go, but you should try doing it yourself. it's pretty easy to google things like "on button click" etc.
var total = 0;
$('.js_send').click(function(){
total += parseInt($('.number').val());
$('.total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" class="number"/>
<input type="button" value="send" class="js_send"/>
<div class="total">0</div>
Here's a JQuery free version
var oldInput = 0,
newInput,
outPut;
document.querySelector("#showSum").onclick = function() {
newInput = parseInt(document.querySelector("#newInput").value),
outPut = newInput + oldInput,
oldInput = outPut,
document.querySelector("#result").innerHTML = outPut;
};
#result {
width: 275px;
height: 21px;
background: #ffb6c1;
}
<input type="number" value="0" id="newInput">
<button id="showSum">Show Results</button>
<br>
<div id="result"></div>
Here is the solution to your problem. Put all below code into a html file and name it as index.html, then run the html page.
<html>
<head>
<title></title>
</head>
<body>
Output : <label id="output">0</label>
<form method="get" action="index.html">
Your Input: <input type="text" id="TxtNum"/>
<input type="hidden" id="lastvalue" name="lastvalue" />
<input type="submit" onclick="return doSum();" value="Sum" />
</form>
<script>
//- get last value from querystring.
var lastvalue = getParameterByName('lastvalue');
if (lastvalue != null) {
document.getElementById("lastvalue").value = lastvalue;
document.getElementById("output").innerHTML = lastvalue;
}
/*
* - function to calculate sum
*/
function doSum() {
var newvalue = 0;
if(document.getElementById("TxtNum").value != '')
newvalue = document.getElementById("TxtNum").value;
var lastvalue = 0;
if(document.getElementById("lastvalue").value != '')
lastvalue = document.getElementById("lastvalue").value;
document.getElementById("lastvalue").value = parseInt(newvalue) + parseInt(lastvalue);
output = parseInt(newvalue) + parseInt(lastvalue);
}
/*
* - function to get querystring parameter by name
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</body>
</html>
If you are doing it in server side, You could have a static variable and update it on button click. More like
public static int prevValue;
public int buttonclick(.....){
int sum = textboxValue + prevValue;
prevValue = textboxValue;
return sum;
}
here is your solution
<script type="text/javascript">
var sum=0;
function summ()
{
localStorage.setItem("value",document.getElementById("text").value);
var v=localStorage.getItem("value");
sum=sum+parseInt(v);
alert(sum);
}
</script>
<html>
<input id="text">
<button id="submit" onclick="summ()">sum</button>
</html>
It will be pretty easy.
Created CodePen
http://codepen.io/anon/pen/eJLNXK
function getResult(){
var myinputValue=document.getElementById("myinput").value;
var resultDiv=document.getElementById("result");
if(myinputValue && !isNaN(myinputValue)){
resultDiv.innerHTML=parseInt(myinputValue) + (resultDiv.innerHTML ? parseInt(resultDiv.innerHTML) : 0);
}
}
<input type="text" id="myinput">
<button id="btngetresult" onclick="getResult()">GetResult</button>
<p>
Result:
<div id="result"></div>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function sum() {
var t1 = parseInt(document.getElementById("t1").value);
var t2 = parseInt(document.getElementById("pre").value);
document.getElementById("result").innerHTML = t1+t2;
document.getElementById("pre").value = t1;
}
</script>
</head>
<body>
<div>
<form method="get" action="">
<input type="text" name="t1" id="t1">
<input type="button" value="get sum" name="but" onclick="sum()">
<input type="hidden" name="pre" id="pre" value="0">
</form>
</div>
<div id="result"></div>
</body>
</html>

adding two numbers in javascript

I am trying to add these two numbers for an hour and can't get the result in the third text field. Please help me achieve this. thank you. also please tell me is there any add() method in javascript?
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style type="text/css">
#cal{
border:3px solid green;
padding: 5px;
width:250px;
text-align: center;
}
</style>
</head>
<body>
<button onclick="add()" id="button">Add</button>
<div id="cal">
<input type="text" value=" " id="num1" size="5">
+
<input type="text" value=" " id="num2" size="5">
=
<input type="text" value=" " id="sum" size="5">
</div>
<script>
function add()
{
var a = document.getElementById("num1").value;
var b = document.getElementById("num2").value;
var ans = a + b ;
document.getElementById("sum").value = ans;
}
</script>
</body>
</html>
The input values are strings not numbers. You have to convert them to numbers with the function parseInt() for integers or parseFloat() if they happen to be decimal numbers :
var a = parseFloat(document.getElementById("num1").value);
var b = parseFloat(document.getElementById("num2").value);
var ans = a + b;
document.getElementById("sum").value = ans;
Check this demo
Use JavaScript Number() Function
function add(){
var a = document.getElementById("num1").value;
var b = document.getElementById("num2").value;
var ans = Number(a) + Number(b) ;
document.getElementById("sum").value = ans;
}

Categories

Resources