This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 1 year ago.
what's the problem in this code? I have tried and can't figure it out. I am a total newbie in HTML, JavaScript, and CSS.
I am wandering around the internet but I think I am missing something and its a small mistake. can you kindly help? I have to learn this for my upcoming projects
here is the code
function result() {
let a = getElementById("constant").value;
let b = getElementById("height").value;
let c = getElementById("freq").value;
let sum = Number(a) + Number(b) + Number(c);
document.getElementById("Calculate").value = sum;
}
<form>
Di-Electric Constant: <input class="text" Placeholder="Enter Value" id="constant" </input>
<br> Di-Electric Height: <input class="text" Placeholder="Enter Value" id="height" </input>
<br> Operational Frequency: <input class="text" Placeholder="Enter Value" id="freq" </input>
<br>
<br>
<input type="text" id="Calculate" </input>
<input type="button" value="Calculate" onclick="result()">
</form>
<br/>
It is document.getElementById(). See: MDN WebDocs: document.getElementById().
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
function result()
{
let a = document.getElementById("constant").value;
let b = document.getElementById("height").value;
let c = document.getElementById("freq").value;
let sum = Number(a) + Number(b) + Number(c);
document.getElementById("Calculate").value = sum;
}
<!DOCTYPE html>
<html>
<head>
<h1>Microstrip Calculator</h1>
<p>Enter the following values in numeric form:</p>
</head>
<body>
<form>
Di-Electric Constant: <input class="text"Placeholder="Enter Value" id="constant"</input>
<br>
Di-Electric Height: <input class="text"Placeholder="Enter Value" id="height"</input>
<br>
Operational Frequency: <input class="text"Placeholder="Enter Value" id="freq"</input>
<br>
<br>
<input type="text"id="Calculate"</input>
<input type="button" value="Calculate" onclick="result()">
</form>
<br/>
</body>
</html>
Related
I tried to validate user input whether user input is a number or string by using isNaN or Type but it is not working. I wrote the if statement inside my function to validate user inputs. I want to user to prompt a number only, not a string. If user input is a string, I would like to pop up an alert to the user.
Can anyone can spot any mistake on my code? Either I put the code incorrectly or I missed something.
function updateTotal(){
var total = 0;
var list = document.getElementsByClassName('input');
var values = [];
for (var i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
if (isNaN(list)) {
alert("Error on input");
}
avgMarks = total / 5;
document.getElementById("total").value = total;
document.getElementById("display").value = avgMarks;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
</head>
<body>
<h1>Get marks</h1>
<div>
<form id="form" method="post">
<label for="marks">Enter your 5 marks: </label><br>
<p>Mark 1</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 4</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 5</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Total 5 marks : </p>
<input type="text" name="totalMarks" id="total" value=""><br>
<p>The average of your marks is : </p>
<input type="text" name="avgMarks" id="display" value="">
<br>
</form>
</div>
<!--JavaScript-->
<script src="debug1_with_error.js"></script>
</body>
</html>
The variable list is a NodeList of elements, not what you want to test. The values you want to test are each individual value, one at a time, in your values array, or just isNaN(total), because NaN would come through in the total if any one value were NaN.
I managed to resolve this issue with a different method but i still don't understand why this method didn't work in the first place, i am probably missing something:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
*{padding: 10px}
</style>
</head>
<body>
<script type="text/javascript">
function adding(){
var addnum1=parseInt(num1);
var addnum2=parseInt(num2);
var result=addnum1 + addnum2;
sum.value=result;
}
</script>
<input type="text" name="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" name="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" name="sum">
</body>
</html>
Here is a example of a jsfiddle that you can use to learn better.
https://jsfiddle.net/pxpmp45v/2/
JavaScript:
function adding(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var addnum1=parseInt(num1);
var addnum2=parseInt(num2);
var result= addnum1 + addnum2;
var sum = document.getElementById('sum');
sum.value=result;
}
Your HTML:
<input type="text" id="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" id="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" id="sum">
Few things to note while retrieving value and assigning to a textbox:
You must use getElementById method and assign a id attribute to your element.
<input type="text" id="num1">
You must also retrieve the value of that element in your JavaScript otherwise you will get a NaN. Use this document.getElementById('num2').value instead of document.getElementById('num2')
Debugging help: Try console.log which prints your variables to your browsers console thus helping you identify what is wrong.
While I have seen people accessing the values of inputs directly as global variables it not recommended. I would suggest using getElementsByName to access the values.
function adding(){
document.getElementsByName("sum")[0].value =
parseFloat(document.getElementsByName("num1")[0].value) +
parseFloat(document.getElementsByName("num2")[0].value);
}
<input type="text" name="num1"><br>
<input type="button" value="+" disabled="true"><br>
<input type="text" name="num2"><br>
<input type="button" value="=" onclick="adding()"><br>
<input type="text" name="sum">
num1, num2, and sum aren't declared in your javascript.
You could give them IDs like
<input type="text" id="num1">
<input type="text" id="num2">
<input type="text" id="sum">
And then access them with document.getElementById()
function adding(){
var addnum1 = parseInt(document.getElementById('num1').value);
var addnum2 = parseInt(document.getElementById('num2').value);
var result = addnum1 + addnum2;
document.getElementById('sum').value = result;
}
I am trying to make a simple html page with two text boxes and an a button that adds the two numbers together when clicked. In my output, I am only getting [object HTMLInputElement].
function addNumbers(A, B){
var answer = A + B;
document.getElementById("testResult").innerHTML = answer;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers(varA, varB)">
<h1 id="testResult"></h1>
Any help would be appreciated. I tried changing .innerHTML to .value already but then I get nothing at all as a result.
I assume you want the mathematical sum and not the string concatenation. If that's the case, you can use the following:
UPDATE based on comment:
function addNumbers(elem1, elem2) {
var a = document.getElementById(elem1).value;
var b = document.getElementById(elem2).value;
var c = Number(a) + Number(b);
document.getElementById("testResult").innerHTML = c;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB')"></input>
<h1 id="testResult"></h1>
Here's a working Fiddle: http://jsfiddle.net/JohnnyEstilles/ex09fx7k/.
Some fixes:
You are adding up the inputs elements instead of their value.
To convert its string value to a number, you can use unary +.
Instead of inline event listeners, better use addEventListener.
var a = document.getElementById('varA'),
b = document.getElementById('varB'),
result = document.getElementById("testResult");
document.getElementById('add').addEventListener('click', function() {
addNumbers(a.value, b.value);
});
function addNumbers(n1, n2){
result.textContent = +n1 + +n2;
}
<input type="text" value="15" id="varA">
<input type="text" value="30" id="varB">
<input type="button" id="add" value="Add">
<h1 id="testResult"></h1>
To learn and study JavaScript, im trying to do a calculator, and as start i tried to do a sum operation by taking 2 input. But somehow there is a problem that i cant see. Can you help me?
Here is the code:
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" name="n1" /><br>
Number 2: <input type="text" name="n2" /><br>
</form>
<button id="b" onclick="func();" />Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum() {
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>
Replace:
function sum() {
With:
function func() {
This prevents you from assigning 2 different types / values to the same variable name.
(You've got an sum function and a sum variable in your question.)
Replace:
document.write(sum);
With
document.getElementById('b').innerHTML = sum;
This snippet adds the result of sum to <p id="b"></p> (So, the result may be: <p id="b">18</p>, for example), instead of arbitrarily adding it to the end of your HTML.
And finally, replace:
Number 1: <input type="text" name="n1"/><br>
Number 2: <input type="text" name="n2"/><br>
With:
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
document.getElementById looks for the id attribute in your HTML, not for the name.
There are two problems:-
Change onclick="func();" to onclick="sum();" , you are calling the wrong/undefined function.
<button id="b" onclick="sum();"/>Sum</button>
Assign input tags id as n1 and n2, you have assigned them as name and are referring to them based on id getElementById()
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" id="n1" name="n1"/><br>
Number 2: <input type="text" id="n2" name="n2"/><br>
</form>
<button id="b" onclick="sum();"/>Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum()
{
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
<html>
<head>
<script>
function calculate(){
var a = parseFloat(frmMain.name.value);
var b = parseFloat(frmMain.Salary.value);
var c = parseFloat(frmMain.taxrate.value);
}
</script>
</head>
<body>
<form name="frmMain">
Name <input type ="text" id="name" /><br />
Salary <input type ="text" id="Salary" /><br />
tax rate <input type ="text" id="taxrate" /><br />
<input type="button" value="calculate" onclick="calculate()" />
<input type="reset" value="Clear" /><br />
Sammary<textarea cols="20" rows="5" ></textarea>
</form>
</body>
</html>
i try to make it like this but i dont know how to get the salary and the name and taxrate put it in the comment or notes place may any body help ?
the program should get the name and taxrate and salary and print it inside the textarea using javascript when i click on calculate ? i dont have an idea how to do this
You can use something like this
DEMO
function calculate(){
var a = frmMain.name.value;
var b = parseFloat(frmMain.Salary.value);
var c = parseFloat(frmMain.taxrate.value);
frmMain.summary.value = "Name :"+a+"\nSalary :"+b+"\nTax Rate :"+c;
}
What you want is to add an id to the textarea, maybe id="texty" after that you can get that elemnt with javascript, like this, var area = document.getElementById('texty'); and from there you use the .innerHTML attribute to set its value.
area.innerHTML = b*c; <- this math isn't what you're after but I used a simple case to show you how its done! :)
If you're more keen on using value then read this post to understand the diffrences between .innerHTML and .value
Also reading the JS docs on MDN is very good reference, I'll put a link in the bottom!
Check out the tinker below!
Tinker.io here
MDN JS Docs
<html>
<head>
<script>
function calculate(){
var a = frmMain.name.value;
var b = parseFloat(frmMain.Salary.value);
var c = parseFloat(frmMain.taxrate.value);
var area = document.getElementById("text");
area.innerHTML='Name : '+a+'\nSalary : '+b+'\nTax Rate : '+c;
}
</script>
</head>
<body>
<form name="frmMain">
Name <input type ="text" id="name" /><br />
Salary <input type ="text" id="Salary" /><br />
tax rate <input type ="text" id="taxrate" /><br />
<input type="button" value="calculate" onclick="calculate()" />
<input type="reset" value="Clear" /><br />
Sammary<textarea cols="20" rows="5" id="text"></textarea>
</form>
</body>
</html>