empty input validation not worked? - javascript

I made a simple calculator with javascript , but when i want to validate input , it
display Nan, and if statement not worked to validate empty input ? How to fix this and how to validate empty input by this form and how to remove the Nan Text displayed after empty input submit ?
let b = document.querySelector("#submit");
b.addEventListener("click", function() {
let c = document.querySelector("#plus").value;
let d = document.querySelector("#minus").value;
let result = document.querySelector(".result");
let output = parseInt(c) + parseInt(d);
result.innerHTML = output;
if(c.value == "" && d.value == "") {
console.log("Wrong");
}
else {
console.log("Well Typed");
}
}
)
body {
display:flex;
align-items:center;
background-color:white;
justify-content:center;
font-family:"Montserrat",sans-serif;
flex-direction:column;
}
button {
background-color:#232324;
border:none;
color:white;
padding:10px 17px;
}
.result {
width:50%;
min-height:50px;
background-color:transparent;
display:flex;
align-items:center;
justify-content:center;
flex-direction:row;
}
input {
margin: 20px 0;
padding:10px;
color:black;
background-color:lightgray;
border:none;
}
<body>
<input type="number" placeholder = ""id = "plus">
<input type="number" id = "minus">
<div class="row">
<button id="submit">
+
</button>
<button id="submit">
-
</button>
<button id="submit">
x
</button>
<button id="submit">
÷
</button>
</div>
<span class="result">1</span>
</body>

let b = document.querySelector("#submit");
b.addEventListener("click", function() {
let c = document.querySelector("#plus").value;
let d = document.querySelector("#minus").value;
if(c !== "" && d !== ""){
let result = document.querySelector(".result");
let output = parseInt(c) + parseInt(d);
result.innerHTML = output;
console.log("Well Typed");
}
else{
console.log("Wrong");
}
}
)
body {
display:flex;
align-items:center;
background-color:white;
justify-content:center;
font-family:"Montserrat",sans-serif;
flex-direction:column;
}
button {
background-color:#232324;
border:none;
color:white;
padding:10px 17px;
}
.result {
width:50%;
min-height:50px;
background-color:transparent;
display:flex;
align-items:center;
justify-content:center;
flex-direction:row;
}
input {
margin: 20px 0;
padding:10px;
color:black;
background-color:lightgray;
border:none;
}
<body>
<input type="number" placeholder = ""id = "plus">
<input type="number" id = "minus">
<div class="row">
<button id="submit">
+
</button>
<button id="submit">
-
</button>
<button id="submit">
x
</button>
<button id="submit">
÷
</button>
</div>
<span class="result">1</span>
</body>

The following line already gets the value of the #plus element.
let c = document.querySelector("#plus").value;
Therefore, in the if() statement, there is no need to call .value again;
# wrong
if(c.value == "" && d.value == "") {
#improved
if(c == "" || d == "") {
Improved Code Snippet;
let b = document.querySelector("#submit");
b.addEventListener("click", function() {
let c = document.querySelector("#plus").value;
let d = document.querySelector("#minus").value;
if (c == "" || d == "") {
console.log("Wrong");
} else {
console.log("Well Typed");
let result = document.querySelector(".result");
let output = parseInt(c) + parseInt(d);
result.innerHTML = output;
}
});
body {
display:flex;
align-items:center;
background-color:white;
justify-content:center;
font-family:"Montserrat",sans-serif;
flex-direction:column;
}
button {
background-color:#232324;
border:none;
color:white;
padding:10px 17px;
}
.result {
width:50%;
min-height:50px;
background-color:transparent;
display:flex;
align-items:center;
justify-content:center;
flex-direction:row;
}
input {
margin: 20px 0;
padding:10px;
color:black;
background-color:lightgray;
border:none;
}
<body>
<input type="number" placeholder="" id="plus">
<input type="number" id="minus">
<div class="row">
<button id="submit">
+
</button>
<button id="submit">
-
</button>
<button id="submit">
x
</button>
<button id="submit">
÷
</button>
</div>
<span class="result">1</span>
</body>
Small notes;
I've changed the && (and) to || (or) since 1 empty input should be 'invalid'
HTML id's are unique, you can't have multiple <button id="submit"> (Read more info)

let b = document.querySelector("#submit");
b.addEventListener("click", function() {
let c = document.querySelector("#plus").value;
let d = document.querySelector("#minus").value;
let result = document.querySelector(".result");
let output = parseInt(c) + parseInt(d) || "";
if(c == "" && d == "") {
console.log("Wrong");
}else {
console.log("Well Typed");
}
result.innerHTML = output;
})
body {
display:flex;
align-items:center;
background-color:white;
justify-content:center;
font-family:"Montserrat",sans-serif;
flex-direction:column;
}
button {
background-color:#232324;
border:none;
color:white;
padding:10px 17px;
}
.result {
width:50%;
min-height:50px;
background-color:transparent;
display:flex;
align-items:center;
justify-content:center;
flex-direction:row;
}
input {
margin: 20px 0;
padding:10px;
color:black;
background-color:lightgray;
border:none;
}
<body>
<input type="number" placeholder = ""id = "plus">
<input type="number" id = "minus">
<div class="row">
<button id="submit">
+
</button>
<button id="submit">
-
</button>
<button id="submit">
x
</button>
<button id="submit">
÷
</button>
</div>
<span class="result">1</span>
</body>

I made a else if statement for this code
when the first input has value and the second input has no value
Any suggestions?
if (c == "" && d == "") {
console.log("Wrong");
error.innerHTML = "<h1>Write Number Please>/h1> ";
}
else if(c == "" && d >=0 || c>= 0 && d=="") {
console.log("write value for all inputs");
}
else {
console.log("Well Typed");
result.innerHTML = output;
}
})

Related

How to have clear button on my calculator using javascript

I am kind of having trouble on making my clear function works on my calculator
This is my HTML:
<input type="button" id="result" value="C" onClick="clr()">
<input type="button" name="greater" value="<" onClick="calcNumbers(greater.value)">
<input type="button" name="divb" value="/" onClick="calcNumbers(divb.value)">
<input type="button" name="mulb" value="*" onClick="calcNumbers(mulb.value)">
and this is my JavaScript
function calcNumbers(result) {
form.displayResult.value = form.displayResult.value + result;
}
Wrap all the input fields inside form tag or div tag and give id to that tag, ... and in script tag add function and rest it as document.getElementById("myForm").reset();
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function Add() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else{
var txtResult = +x + +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Sub() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x - +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Mul() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x * +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Div() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else if (y != 0) {
var txtResult = +x / +y;
}
else {
alert("Second Number Should not be Zero");
}
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
function Clear() {
document.getElementById('txtFirst').value = "";
document.getElementById('txtSecond').value = "";
document.getElementById('txtResult').value = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label> FirstNumber :</label><br />
<input id="txtFirst" type="text" /><br />
<label> Second Number :</label><br />
<input id="txtSecond" type="text" /><br />
<label id="txtResult"></label><br />
<input id="btnAdd" type="button" value="ADD" onclick="Add()"/>
<input id="btnSub" type="button" value="SUB" onclick="Sub()"/><br />
<input id="btnMul" type="button" value="MUL" onclick="Mul()"/>
<input id="btnDiv" type="button" value="DIV" onclick="Div()"/>
<input id="btnClear" type="button" value="Clear" onclick="Clear()"/>
</div>
</form>
</body>
</html>
Calculator image
You can clear the text by setting the value to an empty string.
const form = document.querySelector('.calculator > form');
const handleMemoryClear = (v) => {
const disp = form.querySelector('.display');
disp.value = '';
};
const handleMemoryRecall = (v) => console.log('Implement MEMORY_RECALL');
const handleMemoryAdd = (v) => console.log('Implement MEMORY_ADD');
const handleMemoryRemove = (v) => console.log('Implement MEMORY_REMOVE');
const handleOpAdd = (v) => console.log('Implement OP_ADD');
const handleOpSub = (v) => console.log('Implement OP_SUB');
const handleOpMul = (v) => console.log('Implement OP_MUL');
const handleOpDiv = (v) => console.log('Implement OP_DIV');
const handleOpEval = (v) => console.log('Implement OP_EVAL');
const handleTypeIn = (v) => {
const disp = form.querySelector('.display');
disp.value += v;
};
const handleTypeOp = (v) => {
switch (v) {
case '+': return handleOpAdd();
case '-': return handleOpSub();
case '×': return handleOpMul();
case '÷': return handleOpDiv();
case '=': return handleOpEval();
}
}
const handleTypeFn = (v) => {
switch (v) {
case 'MC': return handleMemoryClear();
case 'MR': return handleMemoryRecall();
case 'M+': return handleMemoryAdd();
case 'M-': return handleMemoryRemove();
}
}
const handleButtonPress = (button, type) => {
switch (type) {
case 'in': return handleTypeIn(button.textContent);
case 'op': return handleTypeOp(button.textContent);
case 'fn': return handleTypeFn(button.textContent);
}
};
const ignoreSubmission = e => e.preventDefault();
const handleFormInput = e => {
if (e.target instanceof HTMLButtonElement && e.target.dataset.type) {
handleButtonPress(e.target, e.target.dataset.type);
}
};
form.addEventListener('submit', ignoreSubmission);
form.addEventListener('click', handleFormInput);
:root {
--root-bg: #222;
--root-fg: #EEE;
--calc-bg: #444;
--calc-border: #888;
--calc-disp-bg: #333;
--calc-disp-fg: #EEE;
--calc-btn-bg: #444;
--calc-btn-fg: #EEE;
--calc-btn-hover-bg: #888;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
background: var(--root-bg);
color: var(--root-fg);
}
.calculator {
display: flex;
padding: 0.25em;
background: var(--calc-bg);
border: thin solid var(--calc-border);
align-items: center;
}
.calc-input {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 0.25em;
}
.calc-input > .display {
grid-column-start: 1;
grid-column-end: 5;
grid-row-start: 1;
grid-row-end: 1;
font-size: 1.5em;
background: var(--calc-disp-bg);
border: thin solid var(--calc-border);
color: var(--calc-disp-fg);
font-family: monospace;
text-align: right;
padding: 0.25em;
}
.calc-key {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.125em;
font-weight: bold;
border: thin solid var(--calc-border);
background: var(--calc-btn-bg);
color: var(--calc-btn-fg);
padding: 0.25em 0;
cursor: pointer;
}
.calc-key:hover {
cursor: pointer;
background: var(--calc-btn-hover-bg);
}
.calc-key[data-type="fn"] {
background: #06D;
}
.calc-key[data-type="fn"]:hover {
background: #08F;
}
.calc-key[data-type="op"] {
background: #D60;
}
.calc-key[data-type="op"]:hover {
background: #F80;
}
<div class="calculator">
<form class="calc-input">
<input type="text" class="display" placeholder="0" />
<button class="calc-key" data-type="fn">MC</button>
<button class="calc-key" data-type="fn">M+</button>
<button class="calc-key" data-type="fn">M-</button>
<button class="calc-key" data-type="fn">MR</button>
<button class="calc-key" data-type="in">7</button>
<button class="calc-key" data-type="in">8</button>
<button class="calc-key" data-type="in">9</button>
<button class="calc-key" data-type="op">÷</button>
<button class="calc-key" data-type="in">4</button>
<button class="calc-key" data-type="in">5</button>
<button class="calc-key" data-type="in">6</button>
<button class="calc-key" data-type="op">×</button>
<button class="calc-key" data-type="in">1</button>
<button class="calc-key" data-type="in">2</button>
<button class="calc-key" data-type="in">3</button>
<button class="calc-key" data-type="op">-</button>
<button class="calc-key" data-type="in">0</button>
<button class="calc-key" data-type="in">.</button>
<button class="calc-key" data-type="op">=</button>
<button class="calc-key" data-type="op">+</button>
</form>
</div>

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>

Javascript understanding function

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 '+'.

In Ajax post method in success part the posting sequence of data and get sequence of data is diff

In my given code i have created dynamically textbox with diff ids and in javascript is have fetch value of textbox one by one till here all things are perfect but when i pass this data from ajax post method to other file the sequence of fetched data will change
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
var i = $('input').size() + 1;
$('#add').click(function() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
$('<div id="d"><input type="text" id="field'+value+'" name="dynamic[]" value="' + i + '" /><br/><input type="text" class="field1" name="dynamic1[]" value="' + i+i + '" /></div> ').fadeIn('slow').appendTo('.inputs');
i++;
});
$('#remove').click(function() {
if(i > 1) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
$('#reset').click(function() {
while(i > 2) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
$('.submit').click(function(){
var number = document.getElementById("number").value;
for(var i=1;i<=number;i++)
{
answers = $('#field'+i).val();
alert(answers);
$.ajax({
type: "POST",
url: " dd.php",
data: {answers:answers},
cache: false,
success: function(html)
{
alert(html);
}
})
}
return false;
});
});
</script>
<style>
.field{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
.field1{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
#d{
display:flex;
}
.submit{
width:110px;
background-color:#FF6;
padding:3px;
border:1px solid #FC0;
margin-top:20px;}
</style>
<body>
<div>
Add | Remove | Reset
<form>
<input type="hidden" id="number" value="0"/>
<div class="inputs">
</div>
<input name="submit" type="button" class="submit" value="Submit">
</form>
</div>
</body>
</html>
The Above code won't work. You missed the class in the first input field, you kept id instead of class name.
$(document).ready(function(){
var i = $('input').size() + 1;
$('#add').click(function()
{
$('<div class="d"><input type="text" class="field" name="dynamic[]" value="' + i + '" /><br/><input type="text" class="field1" name="dynamic1[]" value="' + i+i + '" /></div> ').fadeIn('slow').appendTo('.inputs');
i++;
});
$('#remove').click(function() {
if(i > 1) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
$('#reset').click(function() {
while(i > 2) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
});
</script>
<style>
.field{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
.field1{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
.d{
display:flex;
}
.submit{
width:110px;
background-color:#FF6;
padding:3px;
border:1px solid #FC0;
margin-top:20px;
}
</style>
<body>
<div>
Add | Remove | Reset
<form method="post" action="dd.php">
<div class="inputs">
</div>
<input name="submit" type="submit" class="submit" value="Submit">
</form>
</div>
After Searching i got ans of my question so i feel to share with all so i posting my ans on my question only.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
var i = $('input').size() + 1;
$('#add').click(function()
{
$('<div id="d"><input type="text" id="field" name="dynamic[]" value="' + i + '" /><br/><input type="text" class="field1" name="dynamic1[]" value="' + i+i + '" /></div> ').fadeIn('slow').appendTo('.inputs');
i++;
});
$('#remove').click(function() {
if(i > 1) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
$('#reset').click(function() {
while(i > 2) {
$('.field:last').remove();
$('.field1:last').remove();
i--;
}
});
});
</script>
<style>
.field{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
.field1{
padding:0 0 0 0;
margin: 0 5px 24px 78px;
}
#d{
display:flex;
}
.submit{
width:110px;
background-color:#FF6;
padding:3px;
border:1px solid #FC0;
margin-top:20px;
}
</style>
<body>
<div>
Add | Remove | Reset
<form method="post" action="dd.php">
<div class="inputs">
</div>
<input name="submit" type="submit" class="submit" value="Submit">
</form>
</div>
</body>
</html>
dd.php
<?php
foreach($_POST["dynamic"] as $key)
{
echo $key;
}
?>

My javascript stops working after ajax response

For some reason my javascript stops working after I have submitted a POST request.
Here is what is happening. I load my webpage, fill out the form and click 'Click me' :
Next I click ok in the alert popup and the expected result appears:
I fill out the form, but when I try to click the button nothing happens!
Not even my alert popup.
Here are the files I am using.
My CSS, simple2.css :
body, html {
margin:0;
padding;
height:100%
}
a {
font-size:1.25em;
}
#content {
padding:25px;
}
#fade {
display: none;
position:absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #ababab;
z-index: 1001;
-moz-opacity: 0.8;
opacity: .70;
filter: alpha(opacity=80);
}
#modal {
display: none;
position: absolute;
top: 45%;
left: 45%;
width: 64px;
height: 64px;
padding:30px 15px 0px;
border: 3px solid #ababab;
box-shadow:1px 1px 10px #ababab;
border-radius:20px;
background-color: white;
z-index: 1002;
text-align:center;
overflow: auto;
}
#results {
font-size:1.25em;
color:red
}
My HTML, simple2.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="simple2.css">
<title>simple II</title>
</head>
<body>
<div id="fade"></div>
<div id="modal"> <img id="loader" src="images/loading.gif" /> </div>
<div id="results"><!-- Results are displayed here -->
<form method="post" name="start" target="_blank">
<p>Enter thing1: <input type="text" id="thing1" name="thing1" size="10" /></p>
<p>Enter thing2: <input type="text" id="thing2" name="thing2" size="10" /></p>
<p>Enter thing3: <input type="text" id="thing3" name="thing3" size="10" /></p>
<p>Check thing4: <input type="checkbox" id="thing4" name="thing4" value=1>
<input type="hidden" id="state" name="state" value="one" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?0000000000015"></script>
</div>
</body>
</html>
My javascript, simple2.js :
function openModal() {
document.getElementById('modal').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
document.getElementById('fade').style.display = 'none';
}
function loadAjax(url,data, app, epoch, state) {
console.log ("loadAjax urls is [" + url + "] data is [" + data + "]" );
// document.getElementById('results').innerHTML = '';
console.log ("line 14");
openModal();
console.log ("line 16");
var xhr = false;
console.log ("line 18");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
closeModal();
console.log ("line 28");
document.getElementById("results").innerHTML = xhr.responseText;
}
}
console.log ("line 32");
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
console.log ("line 35");
}
}
document.querySelector("#results button").addEventListener("click", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
});
... and finally my cgi script, simple2.py :
#!/usr/bin/env python
import cgi
import os
#import cgitb
import cgitb; cgitb.enable() # for troubleshooting
import time
import calendar
def goto_state_two( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<p>Enter thing5: <input type="text" id="thing5" name="thing5" size="10" /></p>
<p>Enter thing6: <input type="text" id="thing6" name="thing6" size="10" /></p>
<p>Enter thing7: <input type="text" id="thing7" name="thing7" size="10" /></p>
<p>Check thing8: <input type="checkbox" id="thing8" name="thing8" value=1>
<input type="hidden" id="state" name="state" value="two" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
def goto_done( a, b, c, d ):
print """
Thank you!<br>
<li>thing1 is [%s]
<li>thing2 is [%s]
<li>thing3 is [%s]
<li>thing4 is [%s]
<hr>
<form method="post" name="start" target="_blank">
<input type="hidden" id="state" name="state" value="done" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
<script src="simple2.js?%d"></script>
""" % (a,b,c,d,calendar.timegm(time.gmtime()))
form = cgi.FieldStorage()
state = form.getvalue("state")
if state == 'one' :
thing1 = form.getvalue("thing1", "")
thing2 = form.getvalue("thing2", "")
thing3 = form.getvalue("thing3", "")
thing4 = form.getvalue("thing4", "")
goto_state_two( thing1, thing2, thing3, thing4 )
elif state == 'two' :
thing5 = form.getvalue("thing5", "")
thing6 = form.getvalue("thing6", "")
thing7 = form.getvalue("thing7", "")
thing8 = form.getvalue("thing8", "")
goto_done( thing5, thing6, thing7, thing8 )
elif state == 'done' :
print """
Hurray you did it!<br>
"""
else:
print """
unknown state [%s]
<hr>
""" % ( state )
document.getElementById("results").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "BUTTON") {
// Move Prevent Default into condition to allow
// other events to bubble.
e.preventDefault();
// This is a Button click we have captured
var inputs = document.querySelectorAll("input");
var params = inputs[0].name + "=" + inputs[0].value;
for( var i = 1; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.name;
var value = input.value;
params += "&" + name + "=" + value;
}
alert( params );
loadAjax( "/cgi-bin/simple2.py", encodeURI(params));
}
});

Categories