How to add error message alertbox in the given code? - javascript

<html>
<head>
<script type="text/javascript">
function gcd()
{
var x,y;
x=parseInt(document.myform.n1.value);
y=parseInt(document.myform.n2.value);
if((x>'a' && x<='z') && (y>'a' && y<='z') && (x>'A' && x<='Z') && (y>'A' && y<='Z'))
{
while(x!=y)
{
if(x>y)
x=x-y;
else
y=y-x;
}
document.myform.result.value=x;
}
else
{
alert("Enter valid character ! ");
}
</script>
</head>
<body>
<h1 align="center"><b>gcd of two numbers</b></h1>
<hr color="black">
<center>
Enter two numbers :
<form name="myform">
Number 1 : <input type="text" name="n1" value=""> <br> <br>
Number 2 : <input type="text" name="n2" value=""> <br> <br>
<input type="button" value="Get GCD" onClick="gcd()"> <br> <br>
GCD is : <input type="text" name="result" value="">
</form>
</body>
</html>
The above is an HTML-javascript code but I am trying to add a feature which would pop up an alert box if you enter a special character.Please help me figure out why the above code is not working .I'm a beginner at javascript and need your help.
Thanks in advance :)

Simply do with Change the input type with number .Its only allow the number
function gcd() {
var x, y;
x = document.myform.n1.value;
y = document.myform.n2.value
x = parseInt(x);
y = parseInt(y)
if (x > y) {
x = x - y;
} else {
x = y - x;
}
document.myform.result.value = x;
}
<h1 align="center"><b>gcd of two numbers</b></h1>
<hr color="black">
<center>
Enter two numbers :
<form name="myform">
Number 1 : <input type="number" name="n1" value=""> <br> <br> Number 2 : <input type="number" name="n2" value=""> <br> <br>
<input type="button" value="Get GCD" onClick="gcd()"> <br> <br> GCD is : <input type="number" name="result" value="">
</form>

The best way to not only handle errors but make sure that the text is in the desired format would be to use Regular Expression. Basic validation here could be done as said below by setting input type to number, although is not recommended.
You can always handle errors by Javascript Error Handling.
Would recommend doing more research on the following for your use case and figure out what your ideal case would be. Hope this helps !

Related

Questionnaire scoring based on User's score

I'm a total noob so pardon the errors. I am trying to create a script that returns a new score for User B based on User A's score depending on the results of a 5-point Likert scale questionnaire. Both are firstly inputs at the top of the page, then the questionnaire which changes User B's score is below. It should work like this:Firstly: User A Score = x User B score = yIt rounds User A's score to the nearest 50, then divides it by 50 to create a number we'll call z.E.g User A score = 442, it gets rounded to 450, then divided by 50 = 9.This new number is z. or z =x/50 (to the nearest whole number). Now based on the survey responses, if User A clicks "very poor", it takes the input data for User B's score and subtracts z from it. Then gives a new result below based on the result of the questionnaire after submission such that:Very poor = y-zPoor = y (doesn't change the score)Satisfactory = y+zGood = y+z+1Very good = y+z+2Let me know if this makes sense. I attached a sample code I tried making below but I'm sure it's wrong. It needs to do more than this but this is the bare minimum I want to figure out. Thanks
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
Questionnaire mess around
</h1>
<p>
<label for='ascore' class="inlinelabel">User A Score</label>
<input id="ascore" type="number"> <br>
<br>
<label for='bscore' class="inlinelabel">User B Score</label>
<input id="bscore" type="number">
</p>
<form action="" id="scorecalc" onsubmit="return false;">
<fieldset>
<br>
<legend>Peer Review Questionnaire!</legend>
<h3> Based on your recent project together, how would you rate User B in the following Skills</h3>
<hr>
<label ><strong>Time Management</strong></label>
<br>
<br>
<input type="radio" name="tmscore" value="tmvpoor" />
Very Poor
<input type="radio" name="tmscore" value="tmpoor"/>
Poor
<input type="radio" name="tmscore" value="tmsat" />
Satisfactory
<input type="radio" name="tmscore" value="tmgood"/>
Good
<input type="radio" name="tmscore" value="tmvgood" />
Very Good
<br>
<button onclick="myFunction()" class="button">Submit</button>
</fieldset>
</form>
<h2>
User B New Score </h2>
<p id="result"></p>
<script>
var theForm = document.forms["scorecalc"];
var x = document.getElementByID(ascore).value
var y = document.getElementByID(bscore).value
function closest50(x) {
return Math.round(x/ 50) * 50
}
var z = closest50(x)
var tm_result = new Array();
tm_result["tmvpoor"]=y-z;
tm_result["tmpoor"]=y;
tm_result["tmsat"]=y+z;
tm_result["tmgood"]=y+z+1;
tm_result["tmvgood"]=y+z+2
function myFunction() {
document.getElementById("result").innerHTML = tm_result;
}
</script>
</body>
There is a lot of problems in your code
things that should be inside of function are not
you don't really want an array but object to store key/value pairs
value of input fields is always string, you need to convert it to number before doing mathematical operations with it
document.getElementByID is not a function you want ...ById
you have said that you want to divide x by 50 but you immediately multiply it by 50 back to the original
ascore and bscore in your document.getElementById should be strings
you want to pass string to .innerHTML not an array/object
Here is working code. If you have some questions about it, post a comment below (I have changed only the JS part).
const theForm = document.querySelector('#scorecalc');
function closest50(x) {
return Math.round(x / 50);
}
function myFunction() {
const x = Number(document.getElementById('ascore').value);
const y = Number(document.getElementById('bscore').value);
const choice = document.querySelector('input[type=radio]:checked').value;
const z = closest50(x)
const tm_result = {
tmvpoor: y - z,
tmpoor: y,
tmsat: y + z,
tmgood: y + z + 1,
tmvgood: y + z + 2
};
document.getElementById("result").innerHTML = tm_result[choice];
}
<h1>
Questionnaire mess around
</h1>
<p>
<label for='ascore' class="inlinelabel">User A Score</label>
<input id="ascore" type="number"> <br>
<br>
<label for='bscore' class="inlinelabel">User B Score</label>
<input id="bscore" type="number">
</p>
<form action="" id="scorecalc" onsubmit="return false;">
<fieldset>
<br>
<legend>Peer Review Questionnaire!</legend>
<h3> Based on your recent project together, how would you rate User B in the following Skills</h3>
<hr>
<label ><strong>Time Management</strong></label>
<br>
<br>
<input type="radio" name="tmscore" value="tmvpoor" />
Very Poor
<input type="radio" name="tmscore" value="tmpoor"/>
Poor
<input type="radio" name="tmscore" value="tmsat" />
Satisfactory
<input type="radio" name="tmscore" value="tmgood"/>
Good
<input type="radio" name="tmscore" value="tmvgood" />
Very Good
<br>
<button onclick="myFunction()" class="button">Submit</button>
</fieldset>
</form>
<h2>User B New Score </h2>
<p id="result"></p>

JavaScript pull data from a form and make sure inputs are true

I am working on a basic HTML5 / JavaScript page. I am stuck at getting the line "var textInput = dataEntry.value;" to pull data from the form. As it sits right now whenever I attempt to input a character it will take any character and I get the message "TypeError: Cannot read property 'value' of undefined" can anyone explain to me why I am getting this error?
The code I have now is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = /[^A-Za-z]/g;
if (replacedInput.test(textInput) == false)
throw "You can only enter letters into this field.";
} catch (textInputError) {
window.alert(textInputError)
return false;
} finally {
dataEntry.value = form.toLowerCase()
}
return true;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter()">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter()">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter()">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber()">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber()">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber()">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
As dfsq said, you're not passing anything in when you're calling validateLetter(). You need to pass in the current object. So try this:
onkeypress="validateLetter(this);
You're giving the element as a parameter. Try onkeypress="validateLetter(this)"

JavaScript code displaying in browser when form submitted, not the result of the script

I'm writing a basic calculator in JavaScript, and when I hit "=" on the html form it is returning the entire calculator.js, not the result. I'm not sure why this is happening, I want it to "alert" the answer variable. How can I get this to display correctly?
calculator.html
<!DOCTYPE html>
<html>
<head><title>Calculator</title></head>
<link rel="stylesheet" type="text/css" href="calc.css"/>
<body>
<form>
<p>
<label for="x">First Number</label>
<input type="text" name="x" id="x" />
</p>
<p>
<label for="y">Second Number:</label>
<input type="text" name="y" id="y" />
</p>
<p>
<input type=radio name="Operation" value=Add id="0" /> <label for="0">Add</label>
<input type=radio name="Operation" value=Sub id="1" /> <label for="1">Sub</label>
<input type=radio name="Operation" value=Mult id="2" /> <label for="2">Mult</label>
<input type=radio name="Operation" value=Div id="3" /> <label for="3">Div</label>
</p>
<p>
<input type="submit" value="=" />
<input type="reset" />
</p>
</form>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
calculator.js
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
document.getElementById("x").addEventListener("change", Calculator, false);
document.getElementById("y").addEventListener("change", Calculator, false);
var answer = 0;
document.getElementById(0).addEventListener("click", Calculator, false);
document.getElementById(1).addEventListener("click", Calculator, false);
document.getElementById(2).addEventListener("click", Calculator, false);
document.getElementById(3).addEventListener("click", Calculator, false);
function add(){
answer = x+y;
}
function sub(){
answer = x-y;
}
function mult(){
answer = x*y;
}
function div(){
if(y=0){
alert "Cannot divide by zero"
}
else {answer = x/y}
}
function Calculator(){
if sign == 0{
add();
}
else if sign == 1{
sub();
}
else if sign == 2{
mult();
}
else if sign == 3{
div();
}
alert (answer);
}
This is happening because you've defined your form action as "calculator.js". You only need to include at the end of the HTML code, as you did.
There's no need to set a form or form method since you won't post/get it, only process it via javascript.
Also, the following lines will execute Calculator() whenever you change the value of x or y. I believe that is not what you intend...
document.getElementById("x").addEventListener("change", Calculator, false);
document.getElementById("y").addEventListener("change", Calculator, false);
On time: sign is undefined and alert should be alert(answer). I'll edit my answer with a suggestion for your javascript.
Suggestion: http://jsfiddle.net/xzkqvywf/
wow, there are loads of syntax and logic of errors in the javascript and HTML
some additional ones
in the div function you assign y with the value of zero
if(y=0){
You need to put id's in strings for calls to getElementById
document.getElementById("0")
At no point are you setting the value of "sign" that you use to compare
if (sign == 2)
You're submitted the form with a submit button
<form action="calculator.js" method="GET">
<input type="submit" value="=" />
so pressing the "=" button submits the form and issues a get request for the file "Calculator.js" which it then renders as the output in the browser.
Try removing the form and dealing with the button clicks
<!DOCTYPE html>
<html>
<head><title>Calculator</title></head>
<link rel="stylesheet" type="text/css" href="calc.css"/>
<body>
<div>
<p>
<label for="x">First Number</label>
<input type="text" name="x" id="x" />
</p>
<p>
<label for="y">Second Number:</label>
<input type="text" name="y" id="y" />
</p>
<p>
<input type=radio name="Operation" value=Add id="0" /> <label for="0">Add</label>
<input type=radio name="Operation" value=Sub id="1" /> <label for="1">Sub</label>
<input type=radio name="Operation" value=Mult id="2" /> <label for="2">Mult</label>
<input type=radio name="Operation" value=Div id="3" /> <label for="3">Div</label>
</p>
<p>
<button id="go">=</button>
<button id="reset" />reset</button>
</p>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
and then rewrite the code like this.
(function() {
var x,
y,
sign=0,
answer=0;
document.getElementById("0").addEventListener("click", setSign, false);
document.getElementById("1").addEventListener("click", setSign, false);
document.getElementById("2").addEventListener("click", setSign, false);
document.getElementById("3").addEventListener("click", setSign, false);
document.getElementById("reset").addEventListener("click", reset, false);
document.getElementById("go").addEventListener("click", calc, false);
function reset(e) {
sign = 0;
answer = 0;
}
function setSign(e) {
sign = e.target.id;
}
function add(){
answer = x+y;
}
function sub(){
answer = x-y;
}
function mult(){
answer = x*y;
}
function div(){
if(y==0){
alert("Cannot divide by zero");
return;
}
answer = x/y;
}
function calc(){
x = parseFloat(document.getElementById("x").value);
y = parseFloat(document.getElementById("y").value);
if (sign == 1){
sub();
}
else if (sign == 2){
mult();
}
else if (sign == 3){
div();
}
else {
add();
}
alert(answer);
}
})();
Your javascript code is not correct-
1- Put alert as alert(answer).
2- When you call a function just put name in javascript like
if (sign = 0){
add();
}
function add is already defined avove
Also if and else if conditions are supposed to be in a bracket like
if(sign==0){
}
4- Don't assign values inside if conditions. '=' is used to assign value to a varialbe ,'==' and '===' are used to compare
A HTML form is meant to be submitted to a server(ex: jsp,asp,php pages etc) not to a Javascript file.
If you don't have any server side work to do you can remove the <form> tag and handle the button click event through Javascript. And also the code needs to be modified. Move the <link> tag to <head> section of the page. Don't use the same callback function Calculator() as "click" event handler for every button. Have different callbacks for each of the button (Add, Subtract, Multiply, Divide) "click". And the code
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
has to be moved inside Calculator() function so that you whenever you click "=" present values of input fields with ids x and y will be fetched.

Simple Gallon Calculator

I'm attempting to build a simple web form that takes 3 number inputs and outputs one number based on this formula: (a*b*c)/271).
This is the code I have but nothing is displayed in the output.
Clearly I have almost no clue what I'm doing.
I appreciate all help:
<body>
<img id="logo"src="images/a&l.png" alt="A&L Cesspool"/>
<h1>Grease Trap Gallon Calculator<h2>
<form name=calculator">
<input label="length" type="number" id="a">
<input label="width" type="number" id="b">
<input label="height" type="number" id="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6" >
</form>
<script language="JavaScript" type="text/javascript">
<!--
function gallons() {
var LENGTH = document.calculator.a.value;
var WIDTH = document.calculator.b.value;
var HEIGHT = document.calculator.c.value;
var Total =(LENGTH*WIDTH*HEIGHT)/271;
document.calculator.OUTPUT.value = Total;
}
// -->
</script>
document.forms.calculator. There's no such thing as document.calculator. Also, form elements need name attributes to refer to them in form context, not IDs.
In other news
You have unclosed quotes
You have irregular naming conventions (OUTPUT, a, Total)
You have irregular quotes policy (sometimes you have, sometimes you don't).
So basically
<form name="calculator">
<input label="length" type="number" name="a">
<input label="width" type="number" name="b">
<input label="height" type="number" name="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6">
</form>
function gallons() {
var LENGTH = document.forms.calculator.a.value;
var WIDTH = document.forms.calculator.b.value;
var HEIGHT = document.forms.calculator.c.value;
var Total = (LENGTH * WIDTH * HEIGHT) / 271;
document.forms.calculator.OUTPUT.value = Total;
}
Please grab a proper tutorial from MDN or some similar good source, and start reading.
Your call to document.calculator is not finding the element because its looking by id
change your form definition and it will work
<form name="calculator" id="calculator">

Javascript flashing for a second but not printing in textbox

Amount
<script type="text/javascript">
<!--
function interestVal()
{
var x = document.Amounts.valOfCar.value;
var y = document.Amounts.interestofCar.value;
var z = x+y;
document.Amounts.carInterest.value=z;
}
-->
</script>
</head>
<body background="bg.jpg">
<p>Calculate the cost of your car</p>
<form name = Amounts>
<p>Value of a car <input type="text" value="" name=valOfCar></p>
<p>Interest #15% <input type="text" value="" name=interestofCar></p>
<p>Value + Interest<input type="text" name=carInterest></p>
<p><input type=submit value=Calculate onClick=interestVal()></p>
</form>
</body>
Here you go. I was able to reproduce your problem by just copying your code and running it. This code will run. The principal change I made, which I believe was the source of the problem, was altering from an input of type submit to a button. As a submit, it was doing a postback, which caused the contents of the controls to disappear. Using a button avoids the postback.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function interestVal() {
var x = document.Amounts.valOfCar.value;
var y = document.Amounts.interestofCar.value;
var z = x * y;
document.Amounts.carInterest.value = z;
}
-->
</script>
</head>
<body background="bg.jpg">
<p>Calculate the cost of your car</p>
<form name = "Amounts">
<p>Value of a car <input type="text" name="valOfCar" /></p>
<p>Interest #15% <input type="text" name="interestofCar" /></p>
<p>Value + Interest<input type="text" name="carInterest" /></p>
<p><button type="button" onclick="interestVal();" >Calculate</button></p>
</form>
</body>
</html>
Another potential problem is that by summing x and y, you get their concatenated result, which is probably not what you want. I have changed that to multiplying x times y.
Finally, I have enclosed many of the attribute values in quotes and made the inputs self-closing by ending the with /> instead of >.

Categories