Javascript onkeydown function runs and then display goes away - javascript

first time on the website, anyway my problem is that when I use onkeydown and then use GetChar to check if the enter key was pressed, when operAtion runs,the results of the function only shows on the screen for about a second and then goes away, if the user uses the onclick (clicks the enter button), then this problem doesnt occur. How do I get the result of operAtion to stay on the screen when onkeydown is used. The website is sqrtcalc.comze.com if you want to see what I mean
sqrtcalc
<!DOCTYPE html>
<html>
<head>
<title>Square Root Calculator</title>
<script language="javascript">
function operAtion (form){
var x = form.inputbox.value;
if (isNaN(x)){
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0){
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == ""){
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1/2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
}
function GetChar (event,form){
var keyCode = event.keyCode;
if (keyCode == 13){
operAtion(form);
}
}
</script>
<p></p>
</head>
<body>
<form name="myform" action="" method="get" style = "font-size:50px"><strong>Square Root Calculator</strong></br>
</br>
<input type="text" name="inputbox" value = "" onkeydown = "GetChar(event,this.form);"> </br>
</br>
<input id="button" type="button" name="button" value=" Enter " onclick="operAtion(this.form)" >
</form>
<h1 id = "failsafe"></h1>
</br>
</br>
</br>
<h1 id = "demo"></h1>
</br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>
<img border="0" src="http://counter.rapidcounter.com/counter/1353157574/a"; ALIGN="middle" HSPACE="4" VSPACE="2" style = "padding-left:1400px;">
</body>
</html>

Add this code:
window.onload = function(){
document.getElementById("myform").onsubmit = function(){
return false;
}
}
And add the id attribute id="myform" to the <form> tag.

I refactored your code a little:
I removed your inline functions (inline JS isn't exactly best
practice)
I added an ID to your form so it could be referenced
I added return false; to keep the form from submitting
onsubmit handles both click and enter
Javascript
document.getElementById('myform').onsubmit = function() {
var x = this.inputbox.value;
if (isNaN(x)) {
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0) {
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == "") {
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1 / 2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
return false;
}​
HTML
<form name="myform" action="" method="get" style="font-size:50px" id="myform"><strong>Square Root Calculator</strong><br>
<br>
<input type="text" name="inputbox"> <br>
<br>
<input id="button" type="submit" name="button" value=" Enter ">
</form>
<h1 id="failsafe"></h1>
<h1 id="demo"></h1>
Working demo​

Related

How to stay on same page after click "submit" button, and keep the date I entered in JavaScript

After clicking "submit", stay on this page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code,
Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="my form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">Check My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
In validateForm() I have added else logic which is used for displaying the submitted message and stops the form from being redirected.
Things to do.
Add logic according to your requirement how to submit the form through XMLHttpRequest way. For more see Sending forms through JavaScript
<html>
<head>
<title></title>
</head>
<body>
<form name="my form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">Check My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
<span id="success"></span>
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
} else {
/* ajax logic here and on success message this message is followed*/
document.getElementById('success').innerHTML = "<b>Submitted</b>"
return false; /*stops the form from being submitted normal way*/
}
}
</script>
</body>
</html>

Include a captcha in a Tpl Form

Hi I try to include a Captcha script inside a .Tpl form but if I write the correct email and not fill the captcha Simple the form jump the captcha
The form look to word and the captcha show the numbers. I try different combinations with onsubmit="return checkform(this);" value="{{$submit}}
but nothing look to words
any ideas please?
<div class="generic-content-wrapper-styled">
<h3>{{$title}}</h3>
<p id="lostpass-desc">
{{$desc}}
</p>
<form action="lostpass" method="post" >
<div id="login-name-wrapper">
<label for="login-name" id="label-login-name">{{$name}}</label>
<input type="text" maxlength="60" name="login-name" id="login-name" value="" />
<input type="submit" name="submit" id="lostpass-submit-button" onsubmit="return checkform(this);" value="{{$submit}}"/>
</div>
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<div id="login-extra-end"></div>
<div id="login-submit-end"></div>
</form>
<script type="text/javascript">
// Captcha Script
function checkform(theform){
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
notice( t('No valid account found.') . EOL);
goaway(z_root());
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</div>

What part of this simple Javascript calculator is wrong?

I've recently wrote this simple javascript calculator but it will not work, got any ideas?
function calculateMe() {
var x = document.getElementById("x");
var y = document.getElementById("y");
var e = x + y;
document.getElementById("a").innerHTML = e;
}
<center><input id="x"></input> +
<input id="y"></input><br><br>
<button onclick="calculateMe()">Submit</button><br><br>
<input id="a"></input>
You need to first get the value from the inputs, then set the value like:
function calculateMe() {
var x = +document.getElementById("x").value;
var y = +document.getElementById("y").value;
var e = x + y;
document.getElementById("a").value = e;
}
<input id="x"></input>+
<input id="y"></input>
<br>
<br>
<button onclick="calculateMe()">Submit</button>
<br>
<br>
<input id="a"></input>
The + in the document.getElementById code turns the strings you get into numbers.
<html>
<head>
<script>
function calculateMe() {
var x = parseInt(document.getElementById("x").value);
if(isNaN(x)){
x = 0;
document.getElementById("x").value=x;
alert("The value in the first text box is not a valid number.");
}
var y = parseInt(document.getElementById("y").value);
if(isNaN(y)){
y = 0;
document.getElementById("y").value=y;
alert("The value in the second text box is not a valid number.");
}
var e = x + y;
document.getElementById("a").value = e;
}
</script>
<title>Webpage</title>
</head>
<body>
<center>
<input id="x" type="text"> +
<input id="y" type="text"><br><br>
<button onclick="calculateMe()">Submit</button><br><br>
<input id="a" type="text" readonly>
</center>
</body>
</html>

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Show Value when a variable is entered

im trying to show a value (Staff name) when a variable is entered under the Staff ID
this is a local hta upload into our server
im still learning hope that anyone can help me
here's the script
<title>Test Login</title>
<head>
<HTA:APPLICATION
ID="TestLogin"
APPLICATIONNAME="Login"
SysMenu="no"
BORDER="thin"
CONTEXTMENU="no"
ICON="images/help.ico"
MAXIMIZEBUTTON="no"
MINIMIZEBUTTON="no"
window.resizeTo 400,250
RESIZE="no"
SCROLL="no"
SINGLEINSTANCE="yes"
WINDOWSTATE="normal" />
</head>
<body STYLE="font:14 pt arial; color:white;
filter:progid:DXImageTransform.Microsoft.Gradient
(GradientType=1, StartColorStr='#000000', EndColorStr='#0000FF')">
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;
var unArray = ["4020004", "4020031", "4020025",];
var pwArray = ["4020004", "4020031", "4020025",];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("CALL MAIN WINDOW", 1, false);
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<SCRIPT Language="VBScript">
</script>
<div style="text-align: center;"><img src="#" alt="#" align="middle" width="200" height="200">
<p>
<p>TEST LOGIN</p>
<form name = "myform">
<p>Staff ID <input type="text" name="username"> </p>
**TRYING TO SHOW STAFF NAME HERE WHEN ID IS ENTER**
<p>Password <input type="password" name="pword"></p>
</form>
This is the original script http://www.javascriptkit.com/script/script2/loginpass2.shtml
thanx in advance
Because you are using an external script, i can't really find where you store the ID.
add the following somewhere in your code where you want to show the staff name:
<div class="staff-name-placeholder">Enter ID</div>
modify input:
<p>Staff ID <input type="text" name="username"> </p>
To:
<p>Staff ID <input type="text" name="username" onchange="updatestaff();"> </p>
add following on the bottom of the page:
<script type="text/javascript">
function updatestaff()
{
document.getElementById('staff-name-placeholder').innerHTML='[PLACE ID]';
}
</script>
It does the following:
binds a listener when the input 'username' is changed.
searches the element with id 'staff-name-placeholder'
replaces the HTML inside the element with '[PLACE ID]'.
Of course, the real id isn't given yet, you must pass it through your other script.
I hope this helps a little bit.

Categories