Not able to read entered number in javascript - javascript

I am just starting to use JavaScript and this seems to be really a beginner question. I am trying to make a web page where user can input a number and be able to square it. I have been able to write following code which shows the page with prompt and input fields, button to start calculation and an answer area:
<html>
<head>
<script>
function calculate(){
alert("In calculate fn") // NOT REACHING HERE;
var x = document.getElementByName("SNUM");
document.getElementById("answer_area").innerHTML = x * x;
}
</script>
</head>
<body>
<form>
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Enter a number: </td>
<td><input type = "text" name = "SNUM" /></td>
</tr>
</table>
</form>
<br>
<button onclick="calculate()">Square it</button>
<b><u><br><br>Answer:</b></u>
<p id="answer_area"></p> <!-- answer to be placed here; -->
</body>
</html>
However, there is no response when the button is clicked. Where is the problem and how can this be solved. Thanks for your help.

Three things in this line
document.getElementsByName("SNUM")[0].value;
You need to get the element using index since getElementsByName gives a collection. Secondly you need to get the value so use value with it and thirdly there is a typo in your code
function calculate() {
alert("In calculate fn") // NOT REACHING HERE;
var x = document.getElementsByName("SNUM")[0].value;
document.getElementById("answer_area").innerHTML = x * x;
}
<form>
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Enter a number: </td>
<td><input type="text" name="SNUM" /></td>
</tr>
</table>
</form>
<br>
<button onclick="calculate()">Square it</button>
<b><u><br><br>Answer:</u></b>
<p id="answer_area"></p>
<!-- answer to be placed here; -->

Simple, the problem is here:
var x = document.getElementByName("SNUM");
There is no method called getElementByName but rather:
getElementsByName("SNUM")
Change your code to:
<html>
<head>
<script>
function calculate(){
alert("In calculate fn") // NOT REACHING HERE;
var x = document.getElementsByName("SNUM")[0].value;
document.getElementById("answer_area").innerHTML = x * x;
}
</script>
</head>
<body>
<form>
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Enter a number: </td>
<td><input type = "text" name = "SNUM" /></td>
</tr>
</table>
</form>
<br>
<button onclick="calculate()">Square it</button>
<b><u><br><br>Answer:</b></u>
<p id="answer_area"></p> <!-- answer to be placed here; -->
</body>
</html>

1) Use miss s in getElementsByName.
2) getElementsByName method return a NodeList Collection of elements so get first with [0].
3) For get value use of 'value' property.
So Change:
var x = document.getElementByName("SNUM");
To:
var x = document.getElementsByName("SNUM")[0].value;
function calculate(){
alert("In calculate fn") // NOT REACHING HERE;
var x = document.getElementsByName("SNUM")[0].value;
document.getElementById("answer_area").innerHTML = x * x;
}
<form>
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Enter a number: </td>
<td><input type = "text" name = "SNUM" /></td>
</tr>
</table>
</form>
<br>
<button onclick="calculate()">Square it</button>
<b><u><br><br>Answer:</b></u>
<p id="answer_area"></p> <!-- answer to be placed here; -->

Related

output text color changes when value changes

Problem
I have a table that has inputs that the user enters values, JavaScript runs Calc. and displays the output value. To make the user experience better I would like to change the color of the text when the output changes based on the Calculations that JavaScript peforms. Is this possible?
My Effort
I have looked over the Internet and have not found anything other than when entering values into the input, never anything dealing with the output text.
Example Code
http://codepen.io/coryk/pen/rLGZYa
HTML
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Input</td>
<td><input class="input_green" id="input" type="number" value="0"></td>
<td></td>
<td>Output</td>
<td><input class="input_yellow" id="output" readonly type="number" value="10"></td>
</tr>
</table>
</body>
JavaScript
var foo = function(){
var val = parseFloat($('#input').val());
var total = val * 3;
$('#output').val(total);
}
foo();
document.getElementById("input").onchange = (function() {
foo();
});
You already have a class on the input. I suggest you set a default color for the text here via css and work from there. Yellow is difficult to see. I have used blue
If you run the snippet below, you will see that if you enter 1 in the first input box, the output is blue, but when you enter e.g. 4 or 5, as the result is over 10, the output is red.
var foo = function(){
var val = parseFloat($('#input').val());
var total = val * 3;
if(total > 10){
$('.input_blue').css("color", "red");
}
$('#output').val(total);
}
foo();
document.getElementById("input").onchange = (function() {
foo();
});
.input_blue{color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table>
<tr>
<td>Input</td>
<td><input class="input_green" id="input" type="number" value="0"></td>
<td></td>
<td>Output</td>
<td><input class="input_blue" id="output" readonly type="number" value="10"></td>
</tr>
</table>
</body>
Something like this?
var foo = function(){
var val = parseFloat($('#input').val());
var total = val * 3;
$('#output')
.val(total);
.css('color', 'rgb('+[(val^2)%256,(val*5)%256, (val%256)*2].join(',') +')')
}

javaScript multiply two numbers and show the result into third html input

I am trying to take a number from my html form and then multiply it with a number from my JavaScript function and displaying the result in another html input. Want I want is when the user click on the result input area then only the multiplication result shows.
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = y * z;
document.getElementById("bill").innerHTML = x;
}
<table>
<tr>
<td>Total Kms Run</td>
<td><input type="text" id="km" name="km" required>
</tr>
<tr>
<td>Total Bill</td>
<td><input type="text" id = "bill" name="bill" required onclick="myFunction()">
</tr>
</table
You're adding the numbers, not multiplying them :).
That aside, inputs don't have innerHTML, you need to set the value:
document.getElementById("bill").value = x;
Do Change like this
<script type="text/javascript">
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = y * z;
document.getElementById("bill").value = x;
}</script>
You have made many syntax mistakes in html
function myFunction() {
var y = document.getElementById("km").value;
var z = 14;
var x = Number(y) * Number(z);
document.getElementById("bill").value = x;
}
<table>
<tr>
<td>Total Kms Run</td>
<td><input type="text" id="km" name="km" required ></td>
</tr>
<tr>
<td>Total Bill</td>
<td><input type="text" id="bill" name="bill" required onclick="myFunction()"></td>
</tr>
</table>

I'm trying to make text box in javascript, and to send the entered values in a textbox in a array to add them

Created textbox in javascript, need those value to pass in arrays to add them ?
how do I do that ?
I just want my code to be short and simple
I'm stuck!
Code:
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<script type = "text/javascript">
function sum()
{
var sum = [],i=0;
sum[i]= document.getElementById('i+1').value;
alert("sum =" + sum);
}
</script>
<table border=2>
<TR>
<TD>
<input type="text" id="1" /input>
</TD>
<TD>
<input type="text" id="2" /input>
</TD>
</TR>
</table>
<button name="btHello" onclick="sum();">sum</button>
</html>
Usage of Array in this case is not required according to me.I suggest you to do this even without using arrays. This makes your code simple and short
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<script type = "text/javascript">
function sum()
{
var sum= 0;
$('.textbox').each(function() {
sum += Number($(this).val());
});
alert(sum);
}
</script>
<form>
<table border=2>
<TR>
<TD>
Text 1 :<input type="text" class="textbox" id="1" />
</TD>
<TD>
Text 2 :<input type="text" class="textbox" id="2" />
</TD>
</TR>
</table>
Submit : <input type = "submit" name="btHello" onclick="sum();">
</form>
</html>
Hope my example helps. I suggest using jQuery. It makes it much easier.
function foo() {
var s = [];
$(".foo").each(function() {
s.push( $(this).val() );
});
s = s.join(" ");
alert("sum = " + s);
}
$("#btHello").on("click", function() { foo(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border=2>
<tr>
<td>
<input type="text" class="foo" /input>
</td>
<td>
<input type="text" class="foo" /input>
</td>
</tr>
</table>
<button id="btHello">sum</button>
I´m to totally sure what result you want, but this should help you on your way. If its not totally what you are after, please try to explain your goal a bit more. :)
Happy codin'
function sum()
{
var sum = [];
sum.push(document.getElementById('1').value);
sum.push(document.getElementById('2').value);
// sum of all values
totalSum = 0;
for (var i = 0; i < sum.length; i++) {
totalSum += parseInt(sum[i]);
}
alert("sum = " + totalSum);
}
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<table border=2>
<TR>
<TD>
<input type="text" id="1" /input>
</TD>
<TD>
<input type="text" id="2" /input>
</TD>
</TR>
</table>
<button name="btHello" onclick="sum();">sum</button>
</html>

HTML - Invoice: How to add values to text field and calculate total

I was able to create the template, but I'm not sure what to do from here.
When I click my add item button, I want the values to go into the text area I created on the bottom and change the subtotal and total as I keep adding items.
<html>
<head>
<meta charset = "utf-8">
<h1>Invoice Manager</h1>
<style type "text/css">
div {position: absolute;
top: 200px;
left: 90px;
z-index: 1;}
</style>
<script type = "text/javascript">
</script>
</head>
<body>
<table>
<tr>
<td align="right">Item Code:</td>
<td align="left"><input type="text" name="code" /></td>
</tr>
<tr>
<td align="right">Item Name:</td>
<td align="left"><input type="text" name="itemName" /></td>
</tr>
<tr>
<td align="right">Item Cost:</td>
<td align="left"><input type="text" name="cost" /></td>
</tr>
<tr>
<td align="right">Quantity:</td>
<td align="left"><input type="text" name="quantity" /></td>
</tr>
</table>
<div id="AddItemButton">
<td align = "left"><input type="submit" name="Submit" value="Add Item"></td>
</div>
</form>
<br></br> <br></br>
<font size = "5">Current Invoice</font>
<hr style = "height:2px;border:none;color:#333;background-color:#333;"></hr>
<p><label> <br>
<textarea name = "textarea"
rows = "12" cols = "180"></textarea>
</label></p>
<form>
<table>
<tr>
<td align="right">Subtotal:</td>
<td align="left"><input type="text" name="subtotal" /></td>
</tr>
<tr>
<td align="right">Sales Tax:</td>
<td align="left"><input type="text" name="tax" /></td>
</tr>
<tr>
<td align="right">Total:</td>
<td align="left"><input type="text" name="total" /></td>
</tr>
</table>
</form>
<form>
<input type = "button" value = "Add Item" onclick="textarea"/> <input type = "text" id = "cost" size ="20" />
</form>
That's what I have as a template. When I type in Item Code, Item Name, Item Cost and Quantity in those fields, I'd like those values to go in the text area on the bottom. I imagine I would need to write something in the script.
I'm not sure how to achieve this, but I was thinking that the first batch of info the user adds could equal a variable like a
Then the second values inputted could equal b
So let's say the user adds 3 items.
total = (a + b + c)
Or something like that.
Here's an example of what one "Add Item" would do. I'd like these submissions to appear in the text field I created like so
---Item Code--- ---Item Name--- ---Item Cost--- ---Quantity---
3 Dell 499 1
Any ideas on what I could do? I'm at a loss
Thanks
EDIT: I'm adding my script, I'm wondering if there's something wrong with it
<script type = "text/javascript">
function computeCost(){
var code = document.getElementById("code").value;
var a = code; // item code
var itemName = document.getElementById("itemName").value;
var b = itemName; // item name
var cost = document.getElementById("cost").value;
var c = cost; // calculate cost
var quantity = document.getElementById("quantity").value;
var d = quantity; // calculate quantity of items
var subtotal = document.getElementById("subtotal").value;
var e = c * d; // multiplying cost by quantity = subtotal
var tax = document.getElementById("tax").value;
var f = e * .7; // multiplying subtotal by tax(.7) = amount of tax owed
var total = document.getElementById("total").value;
var g = f + e; //adding tax to subtotal = total value
document.getElementByID("yo").value = total;
}
function clear()
{
document.getElementById("a","b","c","d", "e", "f", "g").reset();
} // end of clear
</script>
I dont have much time to give a polished script, but this provides basic functionality
EDIT: added script tags and basic JQUERY things
note that because of loading JQUERY from the internet, it wont work without internet connection, if you wish to use it without internet con, download the script and link it locally
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type = "text/javascript">
$(function(){
var textContent = $('textarea').val();
var textRow = "";
$('input[type=submit]').click(function(){
$('input[type=text]').each(function(){
textRow = textRow+$(this).val()+'\t';
});
textContent = textContent + '\n' + textRow;
textRow = "";
$('textarea').val(textContent);
});
});
</script>
this is just the necessary JS and HTML, nothing fancy:
function id(id){return document.getElementById(id);}
var val1 = 0;
var val2 = 0;
function val(){
val1 = parseInt(id("t1").value);
val2 = parseInt(id("t2").value);
id("total").innerHTML = ((val1 > 0 && val2 > 0))? val1 * val2 : 0;
}
<input id="t1" onkeyup="val()" type="number">
<input id="t2" onkeyup="val()" type="number">
<h1 id="total"></h1>

values are automatically changed after click submit button

I have code here. There are no errors in this code, but when I was tried to execute this, the output is shown just for a fraction of second. After that, the fields are changed to null. I want all the values to be shown, even after clicking the submit button.
<script type="text/javascript">
function calcu() {
var h = parseInt(document.getElementById("height").value);
var w = parseInt(document.getElementById("weight").value);
var r = h + w;
document.getElementById("res").innerHTML = r;
if (r < 50) {
var x = document.getElementById("report");
x.innerHTML = "less 50";
}
if (r > 50) {
var xy = document.getElementById("report");
xy.innerHTML = "high 50";
}
}
<body>
<form onsubmit="calcu();">
<table>
<tr>
<td>Height:</td>
<td>
<input type="text" id="height">
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" id="weight">
</td>
</tr>
<tr>
<td>
<input type="submit" value="CALCULATE">
</td>
<td>
<p id="res"></p>
</td>
</tr>
</table>
<p id="report">REPORT</p>
<p id="tip"></p>
</form>
Show Your Code First for more.
As much i can from your statement is that you have a button which is type submit and your values are not holding because when you click on submit type button it will post your data and find the next where it has to go in action attribute as if you have not given the action attribute (a/c to me ) so its reloading the page which refreshing the whole content that's why your page is not holding the data.
But if you want it to be hold make your button type simple "Button".
I think this will resolve your problem.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" >
function calcu() {
var h = parseInt(document.getElementById("height").value);
var w = parseInt(document.getElementById("weight").value);
var r = h + w;
document.getElementById("res").innerHTML = r;
if (r < 50) {
var x = document.getElementById("report");
x.innerHTML = "less 50";
}
if (r > 50) {
var xy = document.getElementById("report");
xy.innerHTML = "high 50";
}
}
</script>
</head>
<body>
<form id="form1" >
<table>
<tr>
<td>Height:</td>
<td>
<input type="text" id="height" />
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" id="weight"/>
</td>
</tr>
<tr>
<td>
<input type="button" value="CALCULATE" onclick="calcu();" />
</td>
<td>
<p id="res"></p>
</td>
</tr>
</table>
<p id="report">REPORT</p>
<p id="tip"></p>
</form>
This will do good You are calling function on form submit which reloads the page so previous page does not exist thats why is not doing any good so your have to change your button type to button and on button click you can call the function you will get your desired result.

Categories