Javascript understanding function - javascript

Im learning programming on my own and I'm doing an calculator in html/js/css. I've seen this code, but i cant figure out the javascript, and I wanted a little help, if you can explain the javascript to me, like a comment if it is easier to you, I would be very thankfull.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
input[type="button"]{
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #606060), color-stop(1, #606060) );
background:-moz-linear-gradient( center top, #606060 5%, #606060 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#606060', endColorstr='#606060');
background-color:#606060;
border:1px solid #606060;
display:inline-block;
color:#fff;
font-family:Arial;
font-size:50px;
line-height:28px;
text-decoration:none;
text-align:center;
margin-bottom:1.5px;
margin-left: 1.5px;
margin-right:1.5px ;
margin-top:1.5px ;
height: 75px;
}
input[type="button"]{
width: 184px;
}
#btnC{
width:372.7px;
}
#btn0{
width:374.7px;
}
#btn0,#btndecimal,#btndivide {
margin-right: 0.1px;
}
#btn7,#btn4,#btn1,#btn0,#btnequals {
margin-left: 0.01px;
}
#btnequals {
height: 61px;
width: 944px;
margin-top: 3px;
}
input[type="button"]:active {
position:relative;
background:#989898;
}
input:focus {
outline:0;
}
input[type="Text"] {
padding-left: 10px;
margin-bottom: 1.5px;
font-size: 100px;
background-color: #202020 ;n
height:195px;
width: 935px;
border:none;
color:white;
}
body {
background-color: #080808 ;
overflow: hidden;
}
#about {
font-size: 45px;
}
</style>
</head>
<body>
<FORM name="Keypad" action="">
<input name="ReadOut" id="output" type="Text" size=24 value="0" readonly>
<table>
<tr>
<td><input id="btn7" type="Button" value=" 7 " onclick="NumPressed(7)"></td>
<td><input id="btn8" type="Button" value=" 8 " onclick="NumPressed(8)"></td>
<td><input id="btn9" type="Button" value=" 9 " onclick="NumPressed(9)"></td>
<td colspan="2"><input id="btnC" type="Button" value=" C " onclick="Clear()"></td>
</tr>
<tr>
<td><input id="btn4" type="Button" value=" 4" onclick="NumPressed(4)"></td>
<td><input id="btn5" type="Button" value=" 5 "onclick="NumPressed(5)"></td>
<td><input id="btn6" type="Button" value=" 6 " onclick="NumPressed(6)"></td>
<td><input id="btnplusminus" type="Button" value=" +/- " onclick="Neg()"></td>
<td><input id="btnplus" type="Button" value=" + " onclick="Operation('+')"></td>
</tr>
<tr>
<td><input id="btn1" type="Button" value=" 1 " onclick="NumPressed(1)"></td>
<td><input id="btn2" type="Button" value=" 2 " onclick="NumPressed(2)"></td>
<td><input id="btn3" type="Button" value=" 3 " onclick="NumPressed(3)"></td>
<td><input id="btnmultiply" type="Button" value=" * " onclick="Operation('*')"></td>
<td><input id="btnminus" type="Button" value=" - " onclick="Operation('-')"></td>
</tr>
</table>
<input id="btn0" type="Button" value=" 0 " onclick="NumPressed(0)">
<input id="btndecimal" type="Button" value=" . " onclick="Decimal()">
<input id="btndivide" type="Button" value=" / " onclick="Operation('/')">
<input id="about" type="Button" value="About" onclick="myFunction()"></br>
<input id="btnequals" type="Button" value=" = " onclick="Operation('=')">
</FORM>
<script>
var FKeyPad = document.Keypad;
var Accumulate = 0;
var FlagNewNum = false;
var PendingOp = "";
function NumPressed (Num) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
}
else {
if (FKeyPad.ReadOut.value == "0")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
function Operation (Op) {
var Readout = FKeyPad.ReadOut.value;
if (FlagNewNum && PendingOp != "=");
else
{
FlagNewNum = true;
if ( '+' == PendingOp )
Accumulate += parseFloat(Readout);
else if ( '-' == PendingOp )
Accumulate -= parseFloat(Readout);
else if ( '/' == PendingOp )
Accumulate /= parseFloat(Readout);
else if ( '*' == PendingOp )
Accumulate *= parseFloat(Readout);
else
Accumulate = parseFloat(Readout);
FKeyPad.ReadOut.value = Accumulate;
PendingOp = Op;
}
}
function Decimal () {
var curReadOut = FKeyPad.ReadOut.value;
if (FlagNewNum) {
curReadOut = "0.";
FlagNewNum = false;
}
else
{
if (curReadOut.indexOf(".") == -1)
curReadOut += ".";
}
FKeyPad.ReadOut.value = curReadOut;
}
function ClearEntry () {
FKeyPad.ReadOut.value = "0";
FlagNewNum = true;
}
function Clear () {
Accumulate = 0;
PendingOp = "";
ClearEntry();
}
function Neg () {
FKeyPad.ReadOut.value = parseFloat(FKeyPad.ReadOut.value) * -1;
}
function Percent () {
FKeyPad.ReadOut.value = (parseFloat(FKeyPad.ReadOut.value) / 100) * parseFloat(Accumulate);
}
</script>
<script>
function myFunction() {
alert("TegTech 2014");
}
</script>
</body>
</html>

I can answer your clarified question about the variables here, however in the future you will have better results asking smaller, more specific questions. If a question is too broad it is easy to get off topic & can be difficult to answer in this format.
The 4 variables look to be:
FKeyPad: This variable contains a reference to the document's keypad. This is where your input will be coming from.
Accumulate: This variable is used to contain the total of any calculations being performed. When the program is added, this number is added to & when the program uses subtraction it is subtracted from.
FlagNewNum: This is a Boolean value that indicates if there are more operations to be performed after the current one is finished.
PendingOp: Contains the next operation to be performed, for example if the next operation is addition this variable will contain '+'.

Related

Use JS to determine if all form fields are filled and correctly

*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>

first function must complete before calling second function

For my example I have three functions that must execute completely before going to the next function. I know I can place the second function in the first function, etc, but I need the flexibility to execute functions in various orders.
Upon doing research it appears I need to do a "Callback" but don't understand how to apply it to my situation. Here is what I have so far. Of course the way it is it goes through all three functions without stopping other than for the alerts. Can someone help me here or at least point me in the direction I should consider?
<!DOCTYPE html>
<html>
<body>
<h3>Validates Input Values</h3>
<form name='checkout_form'>
<table id="table_form">
<tr>
<td>First Name:</td>
<INPUT type="text" id="xFirstName" STYLE="color: #3366CC; text-align: left; font-family: Times; font-size: 12px; background-color: transparent; border:dotted; border-color:#7b0000; border-width:1px; width:180px" name="first_name" value="" size="14" onKeyup="autotab(this,document.donate_form.last_name)"
maxlength=14 onkeypress="return inputLimiter(event,'NameCharacters')">
</td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<INPUT type="text" id="xLastName" STYLE="color: #3366CC; text-align: left; font-family: Times; font-size: 12px; background-color: transparent; border:dotted; border-color:#7b0000; border-width:1px; width:180px" name="last_name" value="" size="14" onKeyup="autotab(this,document.donate_form.amount)"
maxlength=14 onkeypress="return inputLimiter(event,'NameCharacters')">
</td>
</tr>
<tr>
<td>Zip Code:</td>
<td>
<INPUT type="text" id="xZipCode" STYLE="color: #3366CC; text-align: left;
font-family: Times; font-size: 12px; background-color: transparent; border:dotted; border-color:#7b0000; border-width:1px; width:180px" name="zip" value="" size="14" onKeyup="autotab(this,document.donate_form.amount)" maxlength=14 onkeypress="return inputLimiter(event,'Numbers')">
</td>
</tr>
</table>
</form>
<button onclick="myFunction_Varify()">VALIDATE</button>
<script>
function myFunction_Varify() {
myFunction_firstName();
myFunction_lastName();
myFunction_zipCode();
}
function myFunction_firstName() {
vFirstName = document.getElementById("xFirstName").value;
if (vFirstName == "") {
document.forms['checkout_form'].elements['first_name'].focus();
alert("No FIRST NAME entered");
}
}
function myFunction_lastName() {
vLastName = document.getElementById("xLastName").value;
if (vLastName == "") {
document.forms['checkout_form'].elements['last_name'].focus();
alert("No LAST NAME entered");
return false;
}
}
function myFunction_zipCode() {
vZipCode = document.getElementById("xZipCode").value;
if (vZipCode == "") {
document.forms['checkout_form'].elements['zip'].focus();
alert("No ZIP CODE entered");
return false;
}
}
</script>
</body>
</html>
you are && them
function myFunction_Varify() {
myFunction_firstName() && myFunction_lastName() && myFunction_zipCode();
}
function myFunction_firstName() {
vFirstName = document.getElementById("xFirstName").value;
if (vFirstName == "") {
document.forms['checkout_form'].elements['first_name'].focus();
alert("No FIRST NAME entered");
return false;
}
return true;
}
function myFunction_lastName() {
vLastName = document.getElementById("xLastName").value;
if (vLastName == "") {
document.forms['checkout_form'].elements['last_name'].focus();
alert("No LAST NAME entered");
return false;
}
return true;
}
function myFunction_zipCode() {
vZipCode = document.getElementById("xZipCode").value;
if (vZipCode == "") {
document.forms['checkout_form'].elements['zip'].focus();
alert("No ZIP CODE entered");
return false;
}
return true;
}

How to .search() multiple strings and have at least 1 to then do function?

I'm programming a calculator for my final high school math project and I can't seem to find how to .search() multiple strings and if the element has at least one then it will work.
function pie(val) {
var pi = document.getElementById("display").value.search("/" | "*" | "-" | "+");
if (pi != -1) {
document.getElementById("display").value += val;
}
else {
document.getElementById("display").value = "Please add an operator";
}
}
I want Pi to only execute if there's an operator because if there's none it just adds PI to whatever number is on the screen.
// Clear Function
function c(val) {
document.getElementById("display").value = val;
}
// Insert Number Function
function insert(val) {
document.getElementById("display").value += val;
}
// Equal Function
function equal(val) {
try {
c(eval(document.getElementById("display").value))
}
catch(equal) {
document.getElementById("display").value = "error";
}
}
// Root Function
function root(val) {
var vroot = document.getElementById("display").value;
var rooted = Math.sqrt(document.getElementById("display").value);
var r = document.getElementById("display").value = rooted;
if (vroot< 0) {
document.getElementById("display").value= "no";
}
}
// Pie Fonction
function pie(val) {
var pi = document.getElementById("display").value.search("/" | "*" | "-" | "+");
if (pi != -1) {
document.getElementById("display").value += val;
}
else {
document.getElementById("display").value = "Please add an operator";
}
}
// Power function : fix so power of any number
function power(val) {
var base = document.getElementById("display").value;
document.getElementById("display").value = base * base;
}
// Log Function
function log(val) {
var vlog = document.getElementById("display").value;
var vloged = Math.log(document.getElementById("display").value);
var v = document.getElementById("display").value = vloged;
if (vlog < 0) {
document.getElementById("display").value= "no";
}
}
function cos(val) {
var vroot = document.getElementById("display").value;
var rooted = Math.sqrt(document.getElementById("display").value);
var r = document.getElementById("display").value = "√" + vroot + "=" + rooted;
}
function sin(val) {
var vroot = document.getElementById("display").value;
var rooted = Math.sqrt(document.getElementById("display").value);
var r = document.getElementById("display").value = "√" + vroot + "=" + rooted;
}
function tan(val) {
var vroot = document.getElementById("display").value;
var rooted = Math.sqrt(document.getElementById("display").value);
var r = document.getElementById("display").value = "√" + vroot + "=" + rooted;
}
.calculator {
text-align: center;
}
.display input {
margin-left: 5px;
font-size: 50px;
width: 600px;
height: 100px;
border-radius: 10px;
background-color: rgb(217, 217, 217);
border-color: rgb(230,230,230, .5);
color: rgb(153, 153, 153);
margin-top: 25px;
}
.display input:focus {
outline:0;
}
.button {
background-color: rgb(230, 230, 230, .5);
font-size: 50px;
height: 100px;
width: 100px;
text-align: center;
margin:3px;
color: rgb(153, 153, 153);
border-radius: 10px;
border-color: rgb(230,230,230, .5);
}
.button:hover {
background-color: white;
}
.button:focus {
outline:0;
}
body {
background-color: rgb(204, 204, 204);
}
<!DOCTYPE html>
<html>
<head>
<title> Calculator </title>
</head>
<body>
<div class="calculator">
<div class="display">
<input type="text" id="display">
</div>
<div class="main">
<br>
<center>
<table>
<tr>
<td><input type="button" class="button" value="C" onclick='c("")'></td>
<td><input type="button" class="button" value="π" onclick='pie(Math.PI)'></td>
<td><input type="button" class="button" value="√" onclick='root()'></td>
<td><input type="button" class="button" value="^" onclick='power()'></td>
<td><input type="button" class="button" value="*" onclick='insert("*")'></td>
</tr>
<tr>
<td><input type="button" class="button" value="log" onclick='log()'></td>
<td><input type="button" class="button" value="7" onclick='insert(7)'></td>
<td><input type="button" class="button" value="8" onclick='insert(8)'></td>
<td><input type="button" class="button" value="9" onclick='insert(9)'></td>
<td><input type="button" class="button" value="/" onclick='insert("/")'></td>
</tr>
<tr>
<td><input type="button" class="button" value="cos" onclick='cos()'></td>
<td><input type="button" class="button" value="4" onclick='insert(4)'></td>
<td><input type="button" class="button" value="5" onclick='insert(5)'></td>
<td><input type="button" class="button" value="6" onclick='insert(6)'></td>
<td><input type="button" class="button" value="+" onclick='insert("+")'></td>
</tr>
<tr>
<td><input type="button" class="button" value="sin" onclick='sin()'></td>
<td><input type="button" class="button" value="1" onclick='insert(1)'></td>
<td><input type="button" class="button" value="2" onclick='insert(2)'></td>
<td><input type="button" class="button" value="3" onclick='insert(3)'></td>
<td><input type="button" class="button" value="-" onclick='insert("-")'></td>
</tr>
<tr>
<td><input type="button" class="button" value="tan" onclick='tan()'></td>
<td><input type="button" class="button" value="?" onclick='insert("")'></td>
<td><input type="button" class="button" value="0" onclick='insert(0)'></td>
<td><input type="button" class="button" value="." onclick='insert(".")'></td>
<td><input type="button" class="button" value="=" onclick='equal()'></td>
</tr>
</table>
</center>
</div>
</div>
</body>
</html>
Try to rewrite this line
var pi = document.getElementById("display").value.search("/" | "*" | "-" | "+");
To this:
var pi = ["/", "*", "-", "+"].indexOf(document.getElementById("display").value);
You should use Array.some for this.
It will return true if your value matches any one of the values from Array else false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
search takes a regular expression. If you are looking for any of those, use /[/*+-]/ as the parameter to search. – Mike McCaughan
He commented it so I don't know how to make it so he solved the question.

Javascript - Simple calculator not running

I have started learning javascript prior to work experience with a website coding business. I have coded this, but when i run the .html file, i get a blank web page. I do not know what i have done wrong. Here is the code:
<html>
<body>
<form>
<p><b>CALCULATOR</b></p>
<p><b>Enter a number to continue:</b></p>
<p><input type="text" name="calcbox1"/></p>
<p><b>Enter the function (+, -, *, /):</b></p>
<p><input type="text" name="calcbox2"/></p>
<p><b>Enter another number:</b></p>
<p><input type="text" name="calcbox3"/></p>
<p><input type="button" onclick="check(this.form)" value="Calculate!"/></p>
<p><input type="reset" value="Reset"></p>
<p><b>Answer:</b></p>
<p><input type="text" name="calcbox4"/></p>
</form>
<script>
function check(form) {
var input4 = 0;
if( form.calcbox2.value == "+" ) {
input4 = form.calcbox1.value + form.calcbox3.value;
}
if( input2 == "-" ) {
input4 = form.calcbox1.value - form.calcbox3.value;
}
if( input2 == "*" ) {
input4 = form.calcbox1.value * form.calcbox3.value;
}
if( input2 == "/" ) {
input4 = form.calcbox1.value / form.calcbox3.value;
}
}
document.all.calcbox4.value = input4;
</script>
<script>
document.write(input4);
</script>
</body>
</html>
Thanks in advance for anyone who can help :)
You could assign first the values of the inputs, convert it to number with an unary + and perfor a check for the operator. The assign it with document.getElementById('calcbox4') to the value property of the input.
The reason for a blank page is the last document.write(input4);, which rewites the page.
document.all.calcbox4.value works only for old Internet Explorer. It is not a standard to assign a value.
function check(form) {
var input1 = +form.calcbox1.value,
operator = form.calcbox2.value,
input3 = +form.calcbox3.value,
output = 0;
if (operator == "+") {
output = input1 + input3;
}
if (operator == "-") {
output = input1 - input3;
}
if (operator == "*") {
output = input1 * input3;
}
if (operator == "/") {
output = input1 / input3;
}
document.getElementById('calcbox4').value = output;
}
<form>
<p><b>CALCULATOR</b></p>
<p><b>Enter a number to continue:</b></p>
<p><input type="text" name="calcbox1" /></p>
<p><b>Enter the function (+, -, *, /):</b></p>
<p><input type="text" name="calcbox2" /></p>
<p><b>Enter another number:</b></p>
<p><input type="text" name="calcbox3" /></p>
<p><input type="button" onclick="check(this.form)" value="Calculate!" /></p>
<p><input type="reset" value="Reset"></p>
<p><b>Answer:</b></p>
<p><input type="text" id="calcbox4" /></p>
</form>
You can use simple switch case and in your case you are not converting the text into integer you have to convert text to int using parseint
function check(form) {
var input4 = 0;
//first input value
var input1 = parseInt(form.calcbox1.value);
//thrid input value
var input3 = parseInt(form.calcbox3.value);
switch(form.calcbox2.value)
{
case "+":
input4 = input1 + input3;
break;
case "-":
input4 = input1 - input3;
break;
case "*":
input4 = input1 * input3;
break;
case "/":
input4 = input1 / input3;
break;
}
document.all.calcbox4.value = input4;
}
<html>
<body>
<form>
<p><b>CALCULATOR</b></p>
<p><b>Enter a number to continue:</b></p>
<p><input type="text" name="calcbox1"/></p>
<p><b>Enter the function (+, -, *, /):</b></p>
<p><input type="text" name="calcbox2"/></p>
<p><b>Enter another number:</b></p>
<p><input type="text" name="calcbox3"/></p>
<p><input type="button" onclick="check(this.form)" value="Calculate!"/></p>
<p><input type="reset" value="Reset"></p>
<p><b>Answer:</b></p>
<p><input type="text" name="calcbox4"/></p>
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function clearFields(val)
{
document.getElementById("expression").value=val;
}
function v(val)
{
document.getElementById("expression").value+=val;
}
function eva(e)
{
try
{
clearFields(eval(document.getElementById("expression").value))
}
catch(e)
{
clearFields('Error')
}
}
validate = function(evt)
{
// Check if the keys are numbers and arithmetic operator.
// For a cross-browser solution, use the "which" property together with keyCode.
if ([8, 13,35,46,37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36,96, 97, 98,99,100,101,102,103,104,105,106,107,109,110,111].indexOf(evt.keyCode || evt.which) == -1)
{
evt.returnValue = false;// Stopping non-numeric keystrokes from reaching an edit field.
if(evt.preventDefault){evt.preventDefault();} // For event cancellation. It tells the user agent that if the event goes unhandled, its default action should not be taken as it normally would be.
}
}
function checkKey(event)
{
if(event.keyCode==13) // Check for ENTER key
eva();
else if(event.keyCode==17) // Check for Ctrl key
clearFields("");
else
validate(event);
}
</script>
</head>
<body>
<div align="center">
</br></br></br></br></br>
<input type="text" id="expression" style="height:50px; width:215px;" onkeydown = "checkKey(event)" />
<p>
<input type="button" value=" / " style="height:50px; width:50px; cursor:pointer; font-weight:bold; background-color: #4CAF50; color:white; border: none; " onclick='v("/")'>
<input type="button" value=" C " style="height:50px; width:160px; background-color: #4CAF50; font-weight:bold; color:white; border: none; " onclick='clearFields("")'>
</p>
<p>
<input type="button" value=" 7 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none; " onclick='v("7")'>
<input type="button" value=" 8 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("8")'>
<input type="button" value=" 9 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("9")'>
<input type="button" value=" * " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("*")'>
</p>
<p>
<input type="button" value=" 4 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("4")'>
<input type="button" value=" 5 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("5")'>
<input type="button" value=" 6 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("6")'>
<input type="button" value=" - " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("-")'>
</p>
<p>
<input type="button" value=" 1 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("1")'>
<input type="button" value=" 2 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("2")'>
<input type="button" value=" 3 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("3")'>
<input type="button" value=" + " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("+")'>
</p>
<p>
<input type="button" value=" 0 " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v("0")'>
<input type="button" value=" . " style="height:50px; width:50px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" onclick='v(".")'>
<input type="button" id= "calc" style="height:50px; width:105px; background-color: #4CAF50; font-weight:bold; color:white; border: none;" value=" = " onclick='eva()'>
</p>
<p align="center">Ctrl to Clear Field</p>
</div>
</body>
</html>

How to assign a class or ID to a table within a JavaScript function?

I have to use HTML, CSS and JavaScript (so no jQuery).
I have created a table that receives JSON data via API. I have a function to show/hide each of the table rows by clicking a check box. I already included the JavaScript function, but I cannot figure out where to place a class or id, so I can connect the function to each of the table rows. Generally, I would add a class to <td> for example, like this: <td class="example"> but in this case it won't work. The code breaks when I do this.
I did search online for hours, but wasn't able to find an answer. I'm not looking for finished code, but rather a hint/help how to achieve this.
This table is created using:
body {
background: white;
}
h1 {
color: black;
font-size: 35px;
text-align: center;
font-family: 'Quicksand', sans-serif;
}
h2 {
font-family: 'Quicksand', sans-serif;
margin-left: 3.3em;
}
table, th , td {
border: none;
border-collapse: collapse;
padding: 15px;
margin-left: 5em;
margin-top: -25em;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
#form {
font-family: 'Quicksand', sans-serif;
margin-left: 5em;
}
#googleMap {
margin-left: 45em;;
margin-right: auto;
}
#chkbox_display {
margin-left: 5em;
margin-top: 3em;
font-family: 'Quicksand', sans-serif;
}
.hidden {
display: none;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<title>Weather App</title>
</head>
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>
<h2>Please enter the following information:</h2>
<form id="form" onsubmit ="return fetchUrl()">
Enter your City:<br>
<input id="weather_city" placeholder="Entere here..."><br>
How to display values: <br>
<select id="weather_scale">
<option value="Metric">Metric Units (Celcius/mm)</option>
<option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
</select><br>
Number of days to show weather:<br>
<select id="weather_numberOfDays">
<option value="1">Today only</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="4">4 days</option>
<option value="5">5 days</option>
</select>
<br><br>
<button onclick="initialize">Submit</button>
</form>
<div id="chkbox_display">
<form action="#">
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Max. Temp.</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Min. Temp</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Rainfall</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Pressure</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Humidity</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Wind Speed</label>
</form>
</div>
<script>
function initAutocomplete() {
weather_city = new google.maps.places.Autocomplete(
(document.getElementById('weather_city')),
{types: ['geocode']});
weather_city.addListener('place_changed');
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>
<script>
var longitude;
var latitude;
function initalize(arr) {
var lon = arr.city.coord.lon;
var lat = arr.city.coord.lat;
var mapProp = {
center:new google.maps.LatLng(lat,lon),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<div id="googleMap" style="width:600px;height:480px;"></div>
<section>
<div id="table">
<!--
<tr>
<td class="hidden">example</td>
<td class="hidden"></td>
<td class="hidden"></td>
</tr>
-->
</div>
</section>
<script>
function getJson(request) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", request, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
}
function fetchUrl() {
var form = document.getElementById("form");
var city = form.weather_city.value;
var value = form.weather_scale.value;
var days = form.weather_numberOfDays.value;
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
getJson(url);
return false;
}
function myFunction(response) {
var arr = JSON.parse(response);
initalize(arr);
var i;
var out = "<table>";
for(i = 0; i < arr.list.length; i++) {
out += "<tr><td>" +
new Date(arr.list[i].dt * 1000) +
"</td></tr>" +
"<tr><td>" +
getIcon(arr.list[i].weather[0].icon) +
"</td><td>" +
arr.list[i].weather[0].description +
"</td><tr>" +
"</tr><td>" +
"Min. Temperature" +
"</td><td>" +
arr.list[i].temp.min +
"</td><tr>" +
"</tr><td>" +
"Max. Temperature" +
"</td><td>" +
arr.list[i].temp.max +
"</td><tr>" +
"</tr><td>" +
"Pressure" +
"</td><td>" +
arr.list[i].pressure +
"</td><tr>" +
"</tr><td>" +
"Windspeed" +
"</td><td>" +
arr.list[i].speed +
"</td><tr>" +
"</tr><td>" +
"Humidity" +
"</td><td>" +
arr.list[i].humidity +
"</td><tr>" +
"</tr><td>" +
"Predicted Rainfall" +
"</td><td>" +
arr.list[i].rain +
"</td><td>";
}
out += "</table>";
document.getElementById("table").innerHTML = out;
}
function getIcon(s) {
return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
</script>
<script>
//function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
function showHide() {
var checkbox = document.getElementById("chkbox");
var hiddenInput = document.getElementsByClassName("hidden");
for(var i = 0; i !=hiddenInput.length; i++) {
if(checkbox.checked) {
hiddenInput[i].style.display = "inline";
} else {
hiddenInput[i].style.display = "none";
}
}
}
</script>
</body>
</html>
The simplest means of achieving this, given the current approach, is to convert the HTML of the <td> opening tags from:
"<tr><td>"
to:
"<tr><td class='example'>"
And then use CSS to style the relevant elements, for example:
.example {
color: #f90;
}
Or, once you've assigned the string of innerHTML, you could simply add this line:
// retrieves the collection of <td> elements from within the
// element with the id of 'table', and uses Array.from() to
// convert that collection into an Array.
// Then iterates over the array of elements using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
// within the anonymous function the 'td' argument is a reference
// to the current array-element of the array over which we're
// iterating.
// here we use the Element.classList API to add the 'example'
// class-name to the existing (if any) class-names of the <td>
// elements:
td.classList.add('example');
});
body {
background: white;
}
h1 {
color: black;
font-size: 35px;
text-align: center;
font-family: 'Quicksand', sans-serif;
}
h2 {
font-family: 'Quicksand', sans-serif;
margin-left: 3.3em;
}
table, th , td {
border: none;
border-collapse: collapse;
padding: 15px;
margin-left: 5em;
margin-top: -25em;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
#form {
font-family: 'Quicksand', sans-serif;
margin-left: 5em;
}
#googleMap {
margin-left: 45em;;
margin-right: auto;
}
#chkbox_display {
margin-left: 5em;
margin-top: 3em;
font-family: 'Quicksand', sans-serif;
}
.hidden {
display: none;
}
.example {
color: #f90;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<title>Weather App</title>
</head>
<body>
<h1>Weather Forecast</h1>
<div id="id01"></div>
<h2>Please enter the following information:</h2>
<form id="form" onsubmit ="return fetchUrl()">
Enter your City:<br>
<input id="weather_city" placeholder="Entere here..."><br>
How to display values: <br>
<select id="weather_scale">
<option value="Metric">Metric Units (Celcius/mm)</option>
<option value="Imperial">Imperial Units (Fahrenheit/inch)</option>
</select><br>
Number of days to show weather:<br>
<select id="weather_numberOfDays">
<option value="1">Today only</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="4">4 days</option>
<option value="5">5 days</option>
</select>
<br><br>
<button onclick="initialize">Submit</button>
</form>
<div id="chkbox_display">
<form action="#">
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Max. Temp.</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Min. Temp</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Rainfall</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Pressure</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Humidity</label>
<input type="checkbox" name="chkbox" id="chkbox"/>
<label for="chkbox">Wind Speed</label>
</form>
</div>
<script>
function initAutocomplete() {
weather_city = new google.maps.places.Autocomplete(
(document.getElementById('weather_city')),
{types: ['geocode']});
weather_city.addListener('place_changed');
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDgIpTEmegx81sL3ukhIdYVQrPkufyjEj4&callback=initalize&libraries=places&callback=initAutocomplete"></script>
<script>
var longitude;
var latitude;
function initalize(arr) {
var lon = arr.city.coord.lon;
var lat = arr.city.coord.lat;
var mapProp = {
center:new google.maps.LatLng(lat,lon),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
</script>
<div id="googleMap" style="width:600px;height:480px;"></div>
<section>
<div id="table">
<!--
<tr>
<td class="hidden">example</td>
<td class="hidden"></td>
<td class="hidden"></td>
</tr>
-->
</div>
</section>
<script>
function getJson(request) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", request, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
}
function fetchUrl() {
var form = document.getElementById("form");
var city = form.weather_city.value;
var value = form.weather_scale.value;
var days = form.weather_numberOfDays.value;
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+city+"&type=accurate,us&mode=json&appid=a0dd3d46dd5b22c0581030acf10af408&units="+value+"&cnt="+days;
getJson(url);
return false;
}
function myFunction(response) {
var arr = JSON.parse(response);
initalize(arr);
var i;
var out = "<table>";
for(i = 0; i < arr.list.length; i++) {
out += "<tr><td>" +
new Date(arr.list[i].dt * 1000) +
"</td></tr>" +
"<tr><td>" +
getIcon(arr.list[i].weather[0].icon) +
"</td><td>" +
arr.list[i].weather[0].description +
"</td><tr>" +
"</tr><td>" +
"Min. Temperature" +
"</td><td>" +
arr.list[i].temp.min +
"</td><tr>" +
"</tr><td>" +
"Max. Temperature" +
"</td><td>" +
arr.list[i].temp.max +
"</td><tr>" +
"</tr><td>" +
"Pressure" +
"</td><td>" +
arr.list[i].pressure +
"</td><tr>" +
"</tr><td>" +
"Windspeed" +
"</td><td>" +
arr.list[i].speed +
"</td><tr>" +
"</tr><td>" +
"Humidity" +
"</td><td>" +
arr.list[i].humidity +
"</td><tr>" +
"</tr><td>" +
"Predicted Rainfall" +
"</td><td>" +
arr.list[i].rain +
"</td><td>";
}
out += "</table>";
document.getElementById("table").innerHTML = out;
Array.from( document.querySelectorAll('#table td') ).forEach(function (td) {
td.classList.add('example');
});
}
function getIcon(s) {
return("<img src=\"http://openweathermap.org/img/w/"+s+".png\"/>");
}
</script>
<script>
//function to show and hide pressure, humidity, etc.... doesnt work yet. not connected!
function showHide() {
var checkbox = document.getElementById("chkbox");
var hiddenInput = document.getElementsByClassName("hidden");
for(var i = 0; i !=hiddenInput.length; i++) {
if(checkbox.checked) {
hiddenInput[i].style.display = "inline";
} else {
hiddenInput[i].style.display = "none";
}
}
}
</script>
</body>
</html>
This does, of course, assume that you're correct that you need to append class-names to the elements; with no explanation of the problem you're trying to solve by adding the class-names it's hard to offer better advice.
I suggest you to use 'knockoutjs' for filling in the table by returned Json data. For your purpose it is really suitable. Its absolutely easy to learn. If you interested in this approach you may ask me questions in comments. And i will trying to help you to solve your particular problem.
Reference: Knockout tutorial

Categories