JavaScript calculator script does't work - javascript

I am learning javascript. Try to make a simple calculator using DOM. I wrote the below script, But my script gives error.
Uncaught TypeError: Cannot read property 'value' of null calculator.html:8
Here is my Script:
<!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<script type="text/javascript">
var f_number = document.getElementById("f_number").value;
var f_number = document.getElementById("s_number").value;
function calculate(opa)
{
if(opa=='+')
{
var result = Number(f_number) + Number(s_number);
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate()" >
<input type="submit" value="-" onclick="calculate()" >
<input type="submit" value="*" onclick="calculate()" >
<input type="submit" value="/" onclick="calculate()" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
</body>
</html>

Full example of working code:
<!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate('+')" >
<input type="submit" value="-" onclick="calculate('-')" >
<input type="submit" value="*" onclick="calculate('*')" >
<input type="submit" value="/" onclick="calculate('/')" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
<script type="text/javascript">
function calculate(opa)
{
var f_number = +document.getElementById("f_number").value;
var s_number = +document.getElementById("s_number").value;
if(opa=='+')
{
var result = f_number + s_number;
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
</body>
</html>

JavaScript is excuted in the order it is encountered.
When you do document.getElementById("f_number").value that DOM node does not yet exist. So it returns null, hence the error message.
Either move your code below the referenced DOM node definitions or run your code on document ready or onload.

It means there are no values for those items:
var f_number = document.getElementById("f_number").value;
var f_number = document.getElementById("s_number").value;
You need to run the script once a value is present/button is clicked as opposed to right away.

Related

Javascript calculation won't start/isn't performed correctly

I'm making a form in which I want to automate some calculations. The form contains a table with some inputs. The Javascript is below the form.
For a reason unknown to me, the calculation won't start or isn't performed correctly.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<form>
<fieldset>
<legend>Inkomsten</legend>
<table>
<tr>
<th scope="col"></th>
<th scope="col">Per maand</th>
<th scope="col">Per jaar</th>
<th scope="col">Totale termijn</th>
</tr>
<tr>
<td>Inkomen</td>
<td><input type="text" name="fldInkomenPerMaand" id="fldInkomenPerMaand"></td>
<td><input type="text" name="fldInkomenPerJaar" id="fldInkomenPerJaar" disabled></td>
<td><input type="text" name="fldInkomenTotaleTermijn" id="fldInkomenTotaleTermijn" disabled></td>
</tr>
<tr>
<td>Vakantiegeld</td>
<td><input type="text" name="vakantiegeldPerMaand" id="vakantiegeldPerMaand" disabled></td>
<td><input type="text" name="vakantiegeldPerJaar" id="vakantiegeldPerJaar"></td>
<td><input type="text" name="vakantiegeldTotaleTermijn" id="vakantiegeldTotaleTermijn" disabled></td>
</tr>
</table>
</fieldset>
</form>
<script type="text/javascript">
function berekeningInkomenPerJaar() {
var inkomenPerMaand = parseInt(document.getElementById("fldInkomenPerMaand").value);
var inkomenPerJaar = document.getElementById("fldInkomenPerJaar");
inkomenPerJaar.value = inkomenPerMaand * 12;
}
</script>
</body>
</html>
The problem is your function is not being run when the input is changed.
It is possible to use the JS addEventListener function to run your code whenever the input value is changed like so:
var inputElement = document.getElementById("fldInkomenPerMaand");
inputElement.addEventListener("change", berekeningInkomenPerJaar);
Your original code with the event listener added in:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<form>
<fieldset>
<legend>Inkomsten</legend>
<table>
<tr>
<th scope="col"></th>
<th scope="col">Per maand</th>
<th scope="col">Per jaar</th>
<th scope="col">Totale termijn</th>
</tr>
<tr>
<td>Inkomen</td>
<td><input type="text" name="fldInkomenPerMaand" id="fldInkomenPerMaand"></td>
<td><input type="text" name="fldInkomenPerJaar" id="fldInkomenPerJaar" disabled></td>
<td><input type="text" name="fldInkomenTotaleTermijn" id="fldInkomenTotaleTermijn" disabled></td>
</tr>
<tr>
<td>Vakantiegeld</td>
<td><input type="text" name="vakantiegeldPerMaand" id="vakantiegeldPerMaand" disabled></td>
<td><input type="text" name="vakantiegeldPerJaar" id="vakantiegeldPerJaar"></td>
<td><input type="text" name="vakantiegeldTotaleTermijn" id="vakantiegeldTotaleTermijn" disabled></td>
</tr>
</table>
</fieldset>
</form>
<script type="text/javascript">
function berekeningInkomenPerJaar() {
var inkomenPerMaand = parseInt(document.getElementById("fldInkomenPerMaand").value);
var inkomenPerJaar = document.getElementById("fldInkomenPerJaar");
inkomenPerJaar.value = inkomenPerMaand * 12;
}
var inputElement = document.getElementById("fldInkomenPerMaand");
inputElement.addEventListener("change", berekeningInkomenPerJaar);
</script>
</body>
</html>

How to calculate the grand total of the column only condition that the contents?

sorry if I ask about things that are similar to before, but I've tried and confused in coding javascipt.
As before I want to calculate the Grand total with the condition that only isNaN will be = 0 and if not NaN = total. When i try condition isNaN it's correct but if not NaN he keep total = 0 why?? i already try with onKeyup, onBlur, and onChange maybe i have wrong in function? Can help me please?
<html>
<head>
<form method = "POST" action="text.php" name="form">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/jquery-ui.css"/>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<!--<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>-->
<script type="text/javascript">
function cal1() {
var a = parseInt($(".qty1").val());
var b = parseInt($(".price1").val());
var c1 = a * b; //a * b
$(".total1").val(c1);
grandtotal();
}
function cal2() {
var a = parseInt($(".qty2").val());
var b = parseInt($(".price2").val());
var c2 = a * b; //a * b
$(".total2").val(c2);
grandtotal();
}
function cal3() {
var a = parseInt($(".qty3").val());
var b = parseInt($(".price3").val());
var c3 = a * b; //a * b
$(".total3").val(c3);
grandtotal();
}
function grandtotal() {
var a1 = parseInt($(".total1").val());
var b1 = parseInt($(".total2").val());
var c1 = parseInt($(".total3").val());
if (isNaN(a1.value) == true)
{
var a1=0;
}
else
{
var a1 = parseInt($(".total1").val());
}
if (isNaN(b1.value) == true)
{
var b1=0;
}
else
{
var b1 = parseInt($(".total2").val());
}
if (isNaN(c1.value) == true)
{
var c1=0;
}
else
{
var c1 = parseInt($(".total3").val());
}
var z = a1+b1+c1; // a1+b1+c1
$(".grandtotal").val(z);
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<table height="51" border="0" cellspacing="2">
<tr>
<td>
<div align="center">Price</div>
</td>
<td>
<div align="center"> Total Price</div>
</td>
</tr>
<tr>
<td>
<input class="qty1" type="text" name="qty1" onblur="qty_blur(this);" onkeyup="cal1();" value="">
</td>
<td>
<input class="price1" type="text" name="price1" onblur="price_blur(this);" onkeyup="cal1();" value="">
</td>
<td>
<input class="total1" type="text" name="total1" value="0" readonly=true onkeyup="grandtotal();">
</td>
</tr>
<tr>
<td>
<input class="qty2" type="text" name="qty2" onblur="qty_blur(this);" onkeyup="cal2();" value="">
</td>
<td>
<input class="price2" type="text" name="price2" onblur="price_blur(this);" onkeyup="cal2();" value="">
</td>
<td>
<input class="total2" type="text" name="total2" value="0" readonly=true onkeyup="grandtotal();">
</td>
</tr>
<tr>
<td>
<input class="qty3" type="text" name="qty3" onblur="qty_blur(this);" onkeyup="cal3();" value="">
</td>
<td>
<input class="price3" type="text" name="price3" onblur="price_blur(this);" onkeyup="cal3();" value="">
</td>
<td>
<input class="total3" type="text" name="total3" value="0" readonly=true onkeyup="grandtotal();">
</td>
</tr>
</table>
</td>
</tr>
</table>
<table>
<tr div class="grandtotal">
<td>
Grand Total :
</td>
<td>
<input class="grandtotal" name="grandtotal" type="text" readonly=true value="">
</td>
</tr>
</div>
</table>
</body>
Numbers don't have a .value property; just check the number itself. Also, isNaN returns a Boolean, so you don't need to check == true.
if (isNaN(a1)) {
var a1=0;
}

Javascript jQuery textbox creation and output

Currently, I have a two table rows with two textboxes. I want to buid a button which allows the user to add and subtract an author row depending on how many they want. Once they increase the amount of authors they need for input, the user clicks on the generate button, the input from the textboxes will be outputed at the bottom of the page. I was trying to pull this off with javascript and jQuery. I am a ten day old student with javascript and jQuery and feel as if I have bit off more than I can chew.
An example of what I want can be found at this lnk: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/. However, I need the input from the textboxes outputed on the same page.
<!DOCTYPE html>
<head>
</head>
<body>
<table>
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br>
<br>
<output id="20"></output>
<br>
<br>
</body>
</html>
<script type=text/javascript>
function myFunction()
{
var firstlast=document.getElementById("1").value;
if (firstlast==null || firstlast=="")
{
firstlast;
}
else if(firstlast!=null || firstlast!="")
{
firstlast=document.getElementById("1").value + ", ";
}
var firstfirst=document.getElementById("2").value;
if (firstfirst==null || firstfirst=="")
{
firstfirst;
}
else if(firstfirst!=null || firstfirst!="")
{
firstfirst=document.getElementById("2").value + ". ";
}
var secondlast=document.getElementById("3").value;
if (secondlast==null || secondlast=="")
{
secondlast;
}
else if(secondlast!=null || secondlast!="")
{
secondlast=document.getElementById("3").value + ", ";
}
document.getElementById("20").innerHTML = firstlast + firstfirst + secondlast;
}
</script>
The jQuery
//wait for the document to be ready
$(document).ready(function()
{
// when generate authors is clicked
$("#generate-authors").click(function()
{
// get the first author row in your table
var author = $(".author-row:first");
// for the amount of authors put into the text box
// insert a copy of the row after the last row
for(i = 0; i < parseInt($("#author-amount").val()); i++)
$(".author-row:last").after(author.clone());
});
// when output data is clicked
$("#output-data").click(function()
{
// go through all the author rows
$(".author-row").filter(function()
{
// add them to the output element
$("#output").append("<p>" + $(this).find("[placeholder=\"Last\"]").val() + ", " + $(this).find("[placeholder=\"First\"]").val() + ".</p>");
});
});
});
The html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// put the script here
</script>
</head>
<body>
<input id="author-amount" type="text" />
<input id="generate-authors" type="button" value="Generate" />
<br />
<input id="output-data" type="button" value="Output Data" />
<table>
<tbody>
<tr class="author-row">
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br />
<output id="output"></output>
</body>
</html>
See this Example might be this is that what you want
HTML
<table id="table">
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<input type="button" id="generat" value="add">
<input type="button" id="remove" value="remove">
<input type="button" id="display" value="display">
<output id="20"></output>
JS
$(document).ready(function(){
$("#generat").click(function(){
var clone = $("#table tr:first").clone();
$("#table tbody:last").append(clone);
});
$("#remove").click(function(){
$("#table tbody tr:last").remove();
});
$("#display").click(function(){
$("#20").html("");
$("table tr").each(function(){
$(this).find("input").each(function(){
$("#20").append(($(this).val()));
});
});
})
});
LINK

HTML/Javascript: How do you change input tag with javascript?

Heres some of what I got, its a calculator, I'mg tryign to call the JS method from the button click events, something wrong though, display won't update.
<script language="javascript" type="text/javascript" src="calculator.js">
var display = document.getElementById('display');
function digit( num ){
if(display == 0){
display.innerHTML = num;
} else {
display.innerHTML = display.innerHTML + "" + num;
}
};
</script>
</head>
<body>
<form name="calculator">
<table width="auto" border="1">
<tr>
<!--<td colspan=4><input id="display" type="text"></td> -->
<td colspan=4><div id="display"></div></td>
</tr>
<tr>
<td>MC</td>
<td>MR</td>
<td>MS</td>
<td><input type="button" value='/' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input type="button" value=7 onclick="javascript:digit(this.value);"></td>
<td><input type="button" value=8 onclick="javascript.digit(this.value);"></td>
<td><input type="button" value=9 onclick="pushButton(this.value);"></td>
<td><input type="button" value='*' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input type="button" value=4 onclick="pushButton(this.value);"></td>
<td><input type="button" value=5 onclick="pushButton(this.value);"></td>
<td><input type="button" value=6 onclick="pushButton(this.value);"></td>
Move
var display = document.getElementById('display');
into your function.
You are calling document.getElementById('display'); before that element (id=display) exists. You can do a variety of things, but the easiest would just be to move the <script> to just before </body>, or at least after id=display
Place 0 in the div Or change the condition in script (display == null )

OnBeforeUnload if qty inputs are differents of 0

I have html table like this :
<table border="1">
<tr>
<td>Prod name </td>
<td>Qty</td>
<td>Add to cart </td>
</tr>
<tr>
<td>product 1 </td>
<td><input name="super_group[961]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="submit" name="Submit" value="Envoyer" /></td>
</tr>
<tr>
<td>product 2 </td>
<td><input name="super_group[962]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="submit" name="Submit2" value="Envoyer" /></td>
</tr>
</table>
and I want to avoid that user quit the page when there is a quantity typed in the qty input fields.
(I have to show a message only if a quantity field is not 0).
With jQuery you could:
$(window).bind('beforeunload', function(e) {
var prompt = false;
$('input.qty').each(function(i, input) {
if ($(input).val() != '0') {
prompt = true;
}
});
if (prompt) {
return e.returnValue = 'Some warning message';
}
});
However https://developer.mozilla.org/en/DOM/window.onbeforeunload
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
Added AJAX when non-zero - NOT tested
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(window).bind('beforeunload', function(e) { // thanks #Ghostoy for the jquery version of this
var nonzero = false;
$(".qty").each(function() { // selector assuming input with class qty
if (this.value>0) {
nonzero=true;
return false; // leave the each
}
});
if (nonzero) return "You have unsaved changes";
});
$("input[id^='sg_']").each(function() {
$(this).bind("keyup", function() {
var disabled = isEmpty(this.value);
$("#bt_"+this.id.split("_")[1]).attr("disabled",disabled);
});
});
$("input[id^='bt_']").each(function() {
var itemId=this.id.split("_")[1]
var val = $("#sg_"+itemId).val()
$(this).attr("disabled",isEmpty(val);
$(this).click(function() {
$.get("add_to_cart.php?item="+itemId+"&qty="+$("#sg_"+itemId).val();
});
});
function isEmpty(val) {
return isNaN(val() || val=="" || val==null;
}
</script>
</head>
<body>
<form action="">
<table border="1">
<tr>
<td>Prod name </td>
<td>Qty</td>
<td>Add to cart </td>
</tr>
<tr>
<td>product 1 </td>
<td><input name="super_group[961]" id="sg_961" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="button" id="bt_961" value="Envoyer" /></td>
</tr>
<tr>
<td>product 2 </td>
<td><input name="super_group[962]" id="sg_962" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="button" id="bt_962" value="Envoyer" /></td>
</tr>
</table>
</form>
</body>
</html>

Categories

Resources