<input type='number' id='number1'/>
This is where I input numbers to later do operations on them (adding up etc). I've got that part covered up, but I wanted to extend this into deleting the total, which is stored in <span id='total'></span>, anytime something new is written in <input/>.
Firstly, I tried addEventListener('input', function());, but the thing is, it works even on input that's not registered. So, since I have <input type='number'/> if I write in 'abcd' etc. nothing changes, but the total is cleaned, because it triggers 'input' event listener. So I did some digging, and found ValueChange event listener, but I can't get it to work (but the value of input obviously changes).
Just to be honest, I checked for solutions, and are responses are either in regards to jQuery or some workarounds.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Kalkulator-JS</title>
<script>
function operation(x) {
var typeOfOp = x;
var n1 = document.getElementById('number1').value;
var n2 = document.getElementById('number2').value;
var total = '';
console.log('Type of operation: ' + typeOfOp);
console.log('Number 1: ' + n1);
console.log('Number 2: ' + n2);
if (isNumber(n1)==false || isNumber(n2)==false) {
alert('Input right data');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typeOfOp) {
case '+':
total = (n1 + n2);
break;
case '-':
total = (n1 - n2);
break;
case '*':
total = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert("You can't divide by 0!!!");
czysczenie();
return false;
}
total = (n1 / n2);
}
document.getElementById('total').innerHTML = total;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function cleanup() {
document.getElementById('total').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var sum = document.getElementById('sum');
var subtract = document.getElementById('subtract');
var multiply = document.getElementById('multiply');
var divide = document.getElementById('divide');
sum.addEventListener('click', function() {
operation(sum.value);
});
subtract.addEventListener('click', function() {
operation(subtract.value);
});
multiply.addEventListener('click', function() {
operation(multiply.value);
});
divide.addEventListener('click', function() {
operation(divide.value);
});
document.getElementById('number1').addEventListener('input', function() {
cleanup();
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Number 1</td>
<td>Number2</td>
</tr>
<tr>
<td><input type='number' id='number1'/></td>
<td><input type='number' id='number2'/></td>
</tr>
</table>
<input type='button' id='sum' value='+'/>
<input type='button' id='subtract' value='-'/>
<input type='button' id='multiply' value='*'/>
<input type='button' id='divide' value='/'/>
<div id='text'>
Total: <span id='total'></span>
</div>
</body>
</html>
If I understand correctly, I believe what you want is addEventListener('keydown', function()). Like so:
document.getElementById('liczba1').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
Explanation:
When using Event Listeners an Event object is passed into the function giving you information about the event that has occurred. In this case the keydown event object has information about which the key has been pressed.
Full Code Example:
function dzialanie(x) {
var typDzialania = x;
var n1 = document.getElementById('liczba1').value;
var n2 = document.getElementById('liczba2').value;
var wynik = '';
console.log('Typ dzialania: ' + typDzialania);
console.log('Liczba 1: ' + n1);
console.log('Liczba 2: ' + n2);
if (isNumber(n1) == false || isNumber(n2) == false) {
alert('Wprowadź poprawne dane');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typDzialania) {
case '+':
wynik = (n1 + n2);
break;
case '-':
wynik = (n1 - n2);
break;
case '*':
wynik = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert('Nie dziel przez 0!!!');
czysczenie();
return false;
}
wynik = (n1 / n2);
}
document.getElementById('wynik').innerHTML = wynik;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function czyszczenie() {
document.getElementById('wynik').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var dodawanie = document.getElementById('dodawanie');
var odejmowanie = document.getElementById('odejmowanie');
var mnozenie = document.getElementById('mnozenie');
var dzielenie = document.getElementById('dzielenie');
dodawanie.addEventListener('click', function() {
dzialanie(dodawanie.value);
});
odejmowanie.addEventListener('click', function() {
dzialanie(odejmowanie.value);
});
mnozenie.addEventListener('click', function() {
dzialanie(mnozenie.value);
});
dzielenie.addEventListener('click', function() {
dzialanie(dzielenie.value);
});
document.getElementById('liczba1').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
document.getElementById('liczba2').addEventListener('keydown', function(e) {
if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
czyszczenie();
});
});
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td>Liczba 1</td>
<td>Liczba 2</td>
</tr>
<tr>
<td>
<input type='number' id='liczba1' />
</td>
<td>
<input type='number' id='liczba2' />
</td>
</tr>
</table>
<input type='button' id='dodawanie' value='+' />
<input type='button' id='odejmowanie' value='-' />
<input type='button' id='mnozenie' value='*' />
<input type='button' id='dzielenie' value='/' />
<div id='tekst'>
Wynik: <span id='wynik'></span>
</div>
</body>
</html>
SOLUTION, thanks to discussion between #Teemu and #imtheman, thanks a lot guys!
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Kalkulator-JS</title>
<script>
function operation(x) {
var typeOfOp = x;
var n1 = document.getElementById('number1').value;
var n2 = document.getElementById('number2').value;
var total = '';
console.log('Type of operation: ' + typeOfOp);
console.log('Number 1: ' + n1);
console.log('Number 2: ' + n2);
if (isNumber(n1)==false || isNumber(n2)==false) {
alert('Input right data');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typeOfOp) {
case '+':
total = (n1 + n2);
break;
case '-':
total = (n1 - n2);
break;
case '*':
total = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert("You can't divide by 0!!!");
czysczenie();
return false;
}
total = (n1 / n2);
}
document.getElementById('total').innerHTML = total;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function cleanup() {
document.getElementById('total').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var sum = document.getElementById('sum');
var subtract = document.getElementById('subtract');
var multiply = document.getElementById('multiply');
var divide = document.getElementById('divide');
sum.addEventListener('click', function() {
operation(sum.value);
});
subtract.addEventListener('click', function() {
operation(subtract.value);
});
multiply.addEventListener('click', function() {
operation(multiply.value);
});
divide.addEventListener('click', function() {
operation(divide.value);
});
document.getElementById('number1').addEventListener('keydown', function(e) {
if (isNumber(e.key)) {
cleanup();
}
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Number 1</td>
<td>Number2</td>
</tr>
<tr>
<td><input type='number' id='number1'/></td>
<td><input type='number' id='number2'/></td>
</tr>
</table>
<input type='button' id='sum' value='+'/>
<input type='button' id='subtract' value='-'/>
<input type='button' id='multiply' value='*'/>
<input type='button' id='divide' value='/'/>
<div id='text'>
Total: <span id='total'></span>
</div>
</body>
</html>
Explanation:
My first bite into it, ValueChange is useless, because it's XUL (dunno what it is yet, but it's useless), gotta use something DOM-related
I have to use one of the event listeners I've tried before (keydown/input), but filter the result
I am bad with using objects, and the keydown event object is much easier to understand than input one (much simplier)
e.key (or event.key) gives me the value of key property of event
So now we need to validate if key pressed is a number or not.
But we can't use inbuilt function of Number(), because empty slots, like Number(' '), equal 0
So I make my own function, isNumber. And voilà.
Related
I am new to learning these languages, and everything looks syntactically correct. The issue I'm having is that the correct button will just keep click as correct rather or not the answer is correct or not. The tables are updating, but I'm not sure where the issue is. The if-else statement looks to be okay (I know I don't need the else if in there). If anyone could help me figure out what is wrong I would appreciate it.
window.onload = function() {
equations();
};
window.onload = equations;
var sum;
var correct = 0,
incorrect = 0;
function equations() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ['+', '-', '÷', 'x'];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length)
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return (sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight() {
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl = document.getElementById('incorrectCount');
sum = equations();
if (userInput = sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput = '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<body>
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function() {
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="button" id="submit" value="Enter" onclick="confirmIfRight()" onclick="document.getElementById('userInput').value = '' " />
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
</body>
The main reason your code wasn't working is because you aren't using the equality operator (==), you are using the assignment operator (=) in your if..else statements. Fixing that alone should resolve the main problem in your question.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
However, this presents another problem in your code immediately: you're comparing sum immediately after reassigning it in confirmIfRight(). A new equation will have been generated prior to the comparison. This means the value in sum will most likely not be correct considering the original equation presented and the answer given.
To resolve this, remove the sum = equations(); line just before the if..else statements:
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Additionally, I do agree that you can remove the else if section and this should capture all cases where the answer does not equal the expected result.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Testing a few times showed that this is all you need to have your code working. Run the code snippet below as an example:
window.onload = equations;
var sum;
var correct=0, incorrect=0;
function equations(){
var a,b,sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a+b , a-b ,a /b ,a *b ];
signs = ['+', '-','÷','x'];
//assign random opperation
let randoArr = Math.floor(Math.random()*solve.length)
sum=solve[randoArr];
showSign=signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return(sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight(){
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl= document.getElementById('incorrectCount');
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function(){
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput"/>
<input type="button" id ="submit" value="Enter"onclick="confirmIfRight()" onclick=
"document.getElementById('userInput').value = '' "/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
There were a few mistakes that you did. The main issue was that you were generating a new equation and sum value every time you call equations function.
So I've saved the value in a new hidden input that is visually hidden from the user. And then compare it to the user input value. There is a plus sign in front of some methods and it is to convert the value to a number. Also, I allowed myself to make a few code naming changes so the code can feel better. Also, you can remove the return statement in the equation method since it has no reason to be there anymore.
let correct = 0,
incorrect = 0;
function generateEquation() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ["+", "-", "÷", "x"];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length);
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById("showMath").innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
document.getElementById("hiddenInput").value = sum;
return sum;
}
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function isCorrect() {
let userInput = +document.getElementById("userInput").value;
const correctEl = document.getElementById("correctCount");
const incorrectEl = document.getElementById("incorrectCount");
if (userInput === +document.getElementById("hiddenInput").value) {
correct++;
correctEl.textContent = correct;
generateEquation();
} else if (userInput == "") {
incorrect++;
incorrect.textContent = incorrect;
generateEquation();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
generateEquation();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById("userInput").value = "";
}
generateEquation();
<!DOCTYPE html>
<html lang="eng">
<head>
<link rel="stylesheet" href="fastmath_style.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial scale = 1" ; />
<title>Fast Math</title>
</head>
<body>
<h1>Welcome to Fast Math!</h1>
<p>A website for solving simple math problems.</p>
<!-- Math Stuff-->
<div id="showMath"></div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="hidden" id="hiddenInput" />
<input
type="button"
id="submit"
value="Enter"
onclick="isCorrect()"
onclick="document.getElementById('userInput').value = '' "
/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount">0</td>
<td id="incorrectCount">0</td>
</tr>
</table>
<script src="./app.js"></script>
</body>
</html>
I've created a basic 4 function calculator in JavaScript and now I need to use an alert to tell the user about any errors. the possible errors are:
One or both input fields are blank
One or both input fields < -9999 or greater than 9999
Divide by zero
Illegal character in either input field. Only 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, and – are allowed.
Code:
function multiplyBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 / num2;
}
function additionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 + num2;
}
function subtractionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 - num2;
}
body {
margin: 30px;
}
<!DOCTYPE html>
<html>
<head>
<body>
<form>
1st Number : <input type="text" id="firstNumber"> 2nd Number: <input type="text" id="secondNumber"> The Result is :
<span id="result"></span>
<br>
</br>
<br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
<input type="button" onClick="additionBy()" Value="Add" />
<input type="button" onClick="subtractionBy()" Value="Sub" />
</br>
</form>
<script type="text/javascript" src="fourth.js">
</script>
</body>
</html>
first of all define the input tag type as number like below
1st Number : <input type="number" id="firstNumber" >
2nd Number: <input type="number" id="secondNumber" >
so, in that case user will not be able to enter invalid input.
secondly, check the divide by zero condition into the function only
There are libraries for validation that you can get but lets start simple. Rework what you have to remove duplicated code and then add functions to do your validation.
This is JUST A START not a complete solution, you have to do work. I will leave it to you to add the OTHER validation you need, but you can see how this is doing it with the couple I added.
function showResults(results) {
document.getElementById("result").innerHTML = results;
}
function multiplyBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 * num2);
}
function divideBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 / num2);
}
function additionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 + num2);
}
function subtractionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 - num2);
}
function actionClicker() {
let number1 = document.getElementById("firstNumber");
let number2 = document.getElementById("secondNumber");
validateNumber(number1);
validateNumber(number2);
var attribute = this.getAttribute("data-myattribute");
var expr = attribute;
switch (expr) {
case 'multiply':
multiplyBy(number1, number2);
break;
case 'division':
divideBy(number1, number2);
break;
case 'subtract':
subtractionBy(number1, number2);
break;
case 'addition':
additionBy(number1, number2);
break;
default:
console.log('Sorry, we do not find ' + expr + '.');
}
}
function showValidationMessage(message) {
alert(message);
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isEmpty(n) {
return n === "";
}
function isInRange(n) {
if (isNumeric(n) && !isEmpty(n)) {
num = parseInt(n, 10);
return num >= -9999 && num <= 9999;
}
return false;
}
function validateNumber(el) {
let hasError = false;
el.classList.remove("has-error");
// add your validation
let message = "get stuff better";
if (!isNumeric(el.value)) {
message = "Not a number.";
hasError = true;
}
if (isEmpty(el.value)) {
message = "Not a number, cannot be empty.";
hasError = true;
}
if (hasError) {
el.classList.add("has-error");
showValidationMessage(message);
}
}
function modifyNumbers(event) {
let el = event.target;
validateNumber(el);
}
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var buttons = document.getElementsByClassName('actions');
// add event listener to buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', actionClicker, false);
}
num1.addEventListener("change", modifyNumbers, false);
num2.addEventListener("change", modifyNumbers, false);
body {
margin: 30px;
}
.buttons {
margin: 2em;
}
label {
padding-right: 1em;
padding-left: 1em
}
.has-error {
background-color: lightpink;
border: solid red 1px;
}
.numbers {
width: 11em;
}
<body>
<form>
<label for="firstNumber">1st Number:</label><input class="numbers" type="number" id="firstNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span><label for="secondNumber">2nd Number:</label><input class="numbers"
type="number" id="secondNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span>
<div><label>The Result is:</label>
<div id="result"></div>
</div>
<div class="buttons">
<button type="button" class="actions" id="multiply" data-myattribute="multiply">Multiply</button>
<button type="button" class="actions" id="divide" data-myattribute="division">Divide</button>
<button type="button" class="actions" id="add" data-myattribute="addition">Add</button>
<button type="button" class="actions" id="subtract" data-myattribute="subtract">Sub</button>
</div>
</form>
</body>
What you are looking for is a validation pattern.
To check if the inputs are valid you can perform checks at the beginning of your math functions. For example
var $num1 = document.getElementById("firstNumber");
var $num2 = document.getElementById("secondNumber");
var $result = document.getElementById("result");
function checkValid(division){
var num1 = $num1.value;
var num2 = $num2.value;
if(num1 == null || num1 > 9999 || num1 < -9999){
return false;
}
if(num2 == null || num2 > 9999 || num2 < -9999){
return false;
}
if(division && num2 === 0){
return false
}
}
function multiplyBy() {
if(check()){
num1 = $num1.value;
num2 = $num2.value;
$result.innerHTML = num1 * num2;
} else {
alert('some error message');
}
}
then in your division function call check(true)
This is just one way to handle it. You could call alert in the check function before returning or even return your error messages from the check function. This should get going in the right direction.
Also I do recommend the <input type="number"> changes by Hasan as well.
I am trying to take two numbers from html and using javascript return sum of both but my num1 and num2 contains HTMLInputElement??
html:
<head>
<script type ="text/javascript" src="functions.js"></script>
</head>
<body>
Value 1: <input type="text" id="tb1" name="tb1"><br/>
Value 2: <input type="text" id="tb2" name="tb2"><br/>
Result: <input type="text" id="tb3" name="tb3"><br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
</body>
javascript:
function validateForm() {
var x = document.getElementById("tb1");
var y = document.getElementById("tb2");
if (x == null || x == "" || y == null || y == "")
{
alert("Value cannot be empty");
return false;
}
else {
//myAdd(x,y);
alert(x + y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").innerHTML = total;
}
}
You are not parsing and adding values from those two inputs, but objects itself. Because of that your if statement block would never run, as you are comparing object to null.Also and you can't set innerHTML of an input,have to use .value.Check the snippet below
parseFloat(x) //you must parseFloat(x.value),
document.getElementById("tb3").value = total; //you have to use .value instead of .innerHTML with input
function validateForm() {
var x = document.getElementById("tb1").value;
var y = document.getElementById("tb2").value;
if (x == null || x === "" || y == null || y === "") {
alert("Value cannot be empty");
return false;
} else {
//myAdd(x,y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").value = total;
}
}
Value 1:
<input type="text" id="tb1" name="tb1">
<br/>Value 2:
<input type="text" id="tb2" name="tb2">
<br/>Result:
<input type="text" id="tb3" name="tb3">
<br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
I have created a conversion table which converts miles to kilometres and kilometres to miles depending on whichever one the user chooses. They input two numbers which indicates the two ranges so if they input 2 and 5 and choose km to m it will then show 2km to 5km converted to miles. However, what I am trying to do is if the user inputs a greater number to start with for instance if you enter 10 and 2 it should still do the same but rather it should go from 10km down to 2km so in descending order, so I know it will be something along the lines of if(rangeStart>rangeEnd){i--;}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function conversion(n) {
if (document.getElementById('mtokm').checked) {
return (n/0.62137).toFixed(2);
}
else {
return (n*0.62137).toFixed(2);
}
}
function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio() && rangeStart != false && rangeEnd != false) {
divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";}
for(i=rangeStart;i<=rangeEnd;i++) {
if(i%2==0)
{
divStr+= "<tr bgcolor=\"yellow\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
else
{
divStr+= "<tr bgcolor=\"green\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
}
document.getElementById("divResult").innerHTML=divStr;
}
else
{
alert("Please make sure you have entered an integer in both text boxes");
}
}
function getnputValue(input) {
var nn = $("input[name=convert]:checked").val()
var myInt = document.getElementById(input).value;
if(myInt == parseInt(myInt))
return parseInt(myInt);
else
return false;
}
function check() {
var radios = document.getElementsByName("choice");
$("input[name=convert]:checked").val()
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
return true;
}
}
return false;
}
function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
End : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/> Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/> Kilometre to Miles
<br>
<br>
<button onClick="conversionTable(getnputValue('rangeTxt'), getnputValue('rangeTxt2'))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
Check whether the end is higher or lower than the start. Then set variables that are used to control the for loop.
var increment, compare;
if (rangeStart <= rangeEnd) {
increment = 1;
compare = function(x, y) {
return x <= y;
};
} else {
increment = -1;
compare = function(x, y) {
return x >= y;
};
}
for (i = rangeStart; compare(i, rangeEnd); i += increment) {
// display code
}
I have been working on this project for school for several weeks now and have came here several times to point me back in the right direction, so thank you for that.
This is the issue I (and my instructor) are struggling over.
I have to create an order form (...yep) where the user must select a computer case, monitor, and printer. The picture must appear next to the selection and the price must update. If everything checks the order submits, if not you get an alert asking to complete the form. You also have the option to reset or clear the form. Everything work wonderfully except the clear function. All fields reset including the price, however the individual values are still being held. If I pick the first option on all sections the total is $1000, after I clear it the total field shows zero. Then, if I pick another option from group A, the values are still totaling with group B and C as if nothing was cleared.
Hope I explained that clearly, here's what I have:
<html>
<head>
<script>
function doSubmit()
{
if (validateText() == false)
{
alert("Please Complete Customer Information");
return;
}
if (validateRadio() == false)
{
alert("Please Select a Case")
return;
}
if (validateRadio1() == false)
{
alert("Please Select a Monitor")
return;
}
if (validateRadio2() == false)
{
alert("Please Select a Printer")
return;
}
alert("Order Accepted. Thank you.");
return;
}
function validateText()
{
var customer = document.Form4.customer.value;
if (customer.length == 0) return false;
var address1 = document.Form4.address1.value;
if (address1.length == 0) return false;
var city = document.Form4.city.value;
if (city.length == 0) return false;
var phone = document.Form4.phone.value;
if (phone.length == 0) return false;
var email = document.Form4.email.value;
if (email.length == 0) return false;
return true;
}
function validateRadio()
{
if (document.Form1.case[0].checked) return true;
if (document.Form1.case[1].checked) return true;
if (document.Form1.case[2].checked) return true;
return false;
}
function validateRadio1()
{
if (document.Form2.screen[0].checked) return true;
if (document.Form2.screen[1].checked) return true;
if (document.Form2.screen[2].checked) return true;
if (document.Form2.screen[3].checked) return true;
return false;
}
function validateRadio2()
{
if (document.Form3.printer[0].checked) return true;
if (document.Form3.printer[1].checked) return true;
if (document.Form3.printer[2].checked) return true;
return false;
}
function doClear()
{
document.Form4.systotal.value = "0.00";
document.Form4.customer.value = "";
document.Form4.address1.value = "";
document.Form4.address2.value = "";
document.Form4.city.value = "";
document.Form4.state.value = "";
document.Form4.zip.value = "";
document.Form4.phone.value = "";
document.Form4.email.value = "";
document.Form1.case[0].checked = false;
document.Form1.case[1].checked = false;
document.Form1.case[2].checked = false;
document.Form2.screen[0].checked = false;
document.Form2.screen[1].checked = false;
document.Form2.screen[2].checked = false;
document.Form2.screen[3].checked = false;
document.Form3.printer[0].checked = false;
document.Form3.printer[1].checked = false;
document.Form3.printer[2].checked = false;
document.Form3.printer[3].checked = false;
formPics(11);
return;
}
var computerCase = 0;
var printer = 0;
var monitor = 0;
var total = 0;
function formPics(radios)
{
switch(radios)
{
case 1:
document.getElementById("pics").innerHTML = "<img src='C1_Game.jpg'>";
computerCase = 600.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 2:
document.getElementById("pics").innerHTML = "<img src='C2_Home.jpg'>";
computerCase = 500.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 3:
document.getElementById("pics").innerHTML = "<img src='C3_Mini.jpg'>";
computerCase = 400.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 4:
document.getElementById("pics2").innerHTML = "<img src='S1_27.jpg'>";
monitor = 350.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 5:
document.getElementById("pics2").innerHTML = "<img src='S2_19.jpg'>";
monitor = 250.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 6:
document.getElementById("pics2").innerHTML = "<img src='S3_17.jpg'>";
monitor = 150.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 7:
document.getElementById("pics2").innerHTML = "<img src='S4_Proj.jpg'>";
monitor = 650.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 8:
document.getElementById("pics3").innerHTML = "<img src='P1_Ink.jpg'>";
printer = 50.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 9:
document.getElementById("pics3").innerHTML = "<img src='P2_Laser.jpg'>";
printer = 80.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 10:
document.getElementById("pics3").innerHTML = "<img src='P3_Color.jpg'>";
printer = 100.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 11:
computerCase = 0;
printer = 0;
monitor = 0;
total = 0;
break;
}
}
function totalclear()
{
if(printer > 0)
printer = 0;
return printer;
}
</script>
<style>
table{ width:800px}
#pics{ float: right;}
#pics2{ float: right;}
#pics3{ float: right;}
</style>
</head>
<body>
<h1 align="center">New System Order Form</h1>
<table border="1" cellpadding="5" align="center">
<tr>
<td>
<form name="Form1" align="left">
<h3>Choose a Case:</h3><div id='pics'></div>
<input name="case" type="radio" onClick='formPics(1)'>Gaming Behemoth ($600.00)<br/>
<input name="case" type="radio" onClick='formPics(2)'>Basic Home Computing ($500.00) <br/>
<input name="case" type="radio" onClick='formPics(3)'>Mini Entertainment Center ($400.00)<br/>
</form>
<br/>
<form name="Form2">
<h3>Choose a Monitor:</h3><div id='pics2'></div>
<input name="screen" type="radio" onClick='formPics(4)'>27" UHD LED ($350.00)<br/>
<input name="screen" type="radio" onClick='formPics(5)'>19"HD LCD ($250.00)<br/>
<input name="screen" type="radio" onClick='formPics(6)'>17"HD LCD ($150.00)<br/>
<input name="screen" type="radio" onClick='formPics(7)'>HD Laser Projector ($650.00) <br/>
</form>
<br/>
<form name="Form3">
<h3>Choose a Printer:</h3><div id='pics3'></div>
<input name="printer" type="radio" onClick='formPics(8)'>Inkjet Printer ($50.00) <br/>
<input name="printer" type="radio" onClick='formPics(9)'>Laser Printer ($80.00)<br/>
<input name="printer" type="radio" onClick='formPics(10)'>Color Laser Printer ($100.00)<br/>
</form>
</td>
<form name="Form4">
<td>
<h3 align="left">System Total: $ <input type="text" name="systotal" size="10" readonly = "readonly" value = "0.00" /></h3>
<hr style="width:100%" />
<h3 align="left">Customer Information:</h3>
<b>Full Name:</b><br/>
<input name="customer" size="45" type="text"><br/>
<b>Address:</b><br/>
<input name="address1" size="45" type="text"><br/>
<input name="address2" size="45" type="text"><br/>
<b>City, State, and Zip:</b><br/>
<input name="city" size="15 type="text">
<input name="state" size="2" type="text">
<input name="zip" size="5" type="text"><br/>
<b>Phone:</b><br/>
<input name="phone" size="40" type="text"><br/>
<b>Email:</b><br/>
<input name="email" size="40" type="text"><br/>
</form>
<hr style="width:100%" />
<br/>
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" Value="Reset Order" onClick="doClear()">
</td>
</tr>
</table>
</body>
</html>
You only have three printers, but you try to clear four. The code in the function doClear gives this error message:
TypeError: document.Form3.printer[3] is undefined
As the code crashes there, the call to formPics(11) is never executed, so the variables are never cleared.