Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem with my if statement that is tasked with checking the input fields and giving me a message that will say if my fields are empty. The problem is I wanted to put it inside of a function so that if the if statement is false it would automatically proceed on with the function and do the task it was meant to do.
As you can see almost all of the functions have the if statement in them.
(I'm making a calculator).
Oh, and please use this basic JavaScript as I did. My knowledge of JavaScript is still not very good and since I'm doing this for a school assignment I should probably use this type of codes.
I will post my code here:
<html>
<head>
<meta charset="utf-8"/>
<script>
function pozdrav()
{
alert("Unesite dva broja te odaberite željenu operaciju:");
}
function brisi()
{
var prvibroj = "";
var drugibroj = "";
var rezultat = "";
document.getElementById("prvibroj").value = prvibroj;
document.getElementById("drugibroj").value = drugibroj;
document.getElementById("rezultat").value = rezultat;
}
function boja(elem)
{
var elem = elem.style.color="red";
}
function staraboja(elem)
{
var elem = elem.style.color="black";
}
function promjena()
{
var rezultat="";
document.getElementById("rezultat").value = rezultat;
}
function plus()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj + drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function minus()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj - drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function mnozenje()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj * drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function djeljenje()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj / drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
</script>
</head>
<body onload="pozdrav()">
<h2>Kalkulator</h2>
<p>Prvi broj:</p>
<input type="text" id="prvibroj" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br />
<p>Drugi broj:</p>
<input type="text" id="drugibroj" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br />
<p>Rezultat:</p>
<input type="text" id="rezultat" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br /> <br />
<input type="button" value="+" onclick="plus()"/>
<input type="button" value="-" onclick="minus()"/>
<input type="button" value="*" onclick="mnozenje()"/>
<input type="button" value="/" onclick="djeljenje()"/>
<input type="button" value="C" onclick="brisi()"/>
</body>
</html>
You are doing this:
var prvibroj = parseInt(document.getElementById("prvibroj").value);
which if document.getElementById("prvibroj").value is empty will set prvibroj to NaN.
Then you are comparing this variable as if it was a string:
if(prvibroj == "" || drugibroj == "")
but if the values are empty it's the same as if (NaN == "" || NaN == "") which will always evaluate to false (NaN is never equal to anything).
So one solution is to check for NaN instead of empty string. For example:
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(isNaN(prvibroj) || isNaN(drugibroj))
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj + drugibroj;
document.getElementById("rezultat").value = rezultat;
}
(and the same for all the functions)
Since you are converting your input value to integer
var drugibroj = parseInt(document.getElementById("drugibroj").value);
the value in drugibroj if the field is blank will be NaN, So you should check for Nan in you if condition instead of ""
if(isNaN(prvibroj) || isNaN(drugibroj))
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
Related
I want to do my JavaScript revision but I got stuck to this question. is there a simple code of html and JavaScript to achieve the answers to these question?
I have tried a simple look of html and JavaScript. but since I am a beginner. some words in this question I may find it hard.
<!DOCTYPE html>
<html>
<script src="js/age.js" language="javascript"></script>
<script>
function myFunction() {
var msg;
if (age == 0 && age <= 2) {
msg = "Toddler";
} else if (age == 3 && age <= 11) {
msg = "Child";
} else if (age == 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
document.getElementById("demo").innerHTML = msg;
}
</script>
<body> Age: <input type="text"> <button onsubmit="return myFunction()">Find Category</button> </body>
</html>
less than or equal is <= - the => is called a fat arrow and used in the arrow function below
onclick is the event, but use an eventListener
You do not store the age from the input field
You do not have a demo element
Here is a better script. Please study it.
window.addEventListener("DOMContentLoaded", () => { // when the page has loaded
const findButton = document.getElementById("find");
const demo = document.getElementById("demo");
findButton.addEventListener("click", e => { // clicking the button
let msg;
let age = document.getElementById("age").value;
if (age >= 0 && age <= 2) {
msg = "Toddler";
} else if (age >= 3 && age <= 11) {
msg = "Child";
} else if (age >= 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
demo.innerHTML = msg;
});
});
Age: <input type="text" id="age"> <button type="button" id="find">Find Category</button>
<span id="demo"></span>
There is a email field where in if we access the site using chrome/IE/Firefox browser it works as expected, But if I access it using IPhone Safari browser the email field reverse the text I entered.
Example image here-
The code for the field Email is
<input
id="emal"
required
type="text"
maxlength="40"
onclick="this.focus();"
onfocus="if(this.value == this.dflt) { this.value='' }; this.onchange();"
onblur="if(this.value.length < 1) { this.value = this.dflt };"
onchange="this.ffoc = true; validate_email();"
onpaste="this.onchange();" oninput="this.onchange();"
onkeypress="this.onchange();">
Validation part of code -
function validate_email() {
if (document.loaded) {
$form[0].$emal.value = "";
$form[0].$emal.valid = null;
updateField($form[1].$emal, $form[1].$emal.value.replace(/\s/ig, ""));
if (isValidEmail($form[1].$emal.value) && $form[1].$emal.value != $form[
1].$emal.dflt) {
$form[0].$emal.value = $form[1].$emal.value;
$form[0].$emal.valid = true;
$form[1].$emal.setAttribute("valid", "true");
} else {
$form[1].$emal.setAttribute("valid", ($form[1].$emal.clik) ? ($form[
1].$emal.required) ? "false" : "warn" : "");
$form[0].$emal.valid = ($form[1].$emal.clik && !$form[1].$emal
.required) ? true : null;
}
$form[1].$emal.$wbox.style.display = ((/false|warn/i).test($form[1]
.$emal.getAttribute("valid"))) ? "block" : "none";
refresh();
}
}
function isValidEmail(str) {
var val = false;
if (str != null) {
var ddStr =
"aero%asia%biz%cat%com%coop%edu%gov%info%int%jobs%mil%mobi%museum%name%net%org%pro%tel%travel%ac%ad%ae%af%ag%cf%cg%ai%al%am%an%ao%aq%ar%as%at%au%aw%ax%az%ba%bb%bd%be%bf%bg%bh%bi%bj%bm%bn%bo%br%bs%bt%bv%bw%by%bz%ca%cc%cd%ch%ci%ck%cl%cm%cn%co%cr%cs%cu%cv%cx%cy%cz%dd%de%dj%dk%dm%do%dz%ec%ee%eg%eh%er%es%et%eu%fi%fj%fk%fm%fo%fr%ga%gb%gd%ge%gf%gg%gh%gi%gl%gm%gn%gp%gq%gr%gs%gt%gu%gw%gy%hk%hm%hn%hr%ht%hu%id%ie%il%im%in%io%iq%ir%is%it%je%jm%jo%jp%ke%kg%kh%ki%km%kn%kp%kr%kw%ky%kz%la%lb%lc%li%lk%lr%ls%lt%lu%lv%ly%ma%mc%md%me%mg%mh%mk%ml%mm%mn%mo%mp%mq%mr%ms%mt%mu%mv%mw%mx%my%mz%na%nc%ne%nf%ng%ni%nl%no%np%nr%nu%nz%om%pa%pe%pf%pg%ph%pk%pl%pm%pn%pr%ps%pt%pw%py%qa%re%ro%rs%ru%tw%tz%ua%ug%uk%us%uy%uz%va%vc%ve%vg%vi%vn%vu%wf%ws%ye%yt%yu%za%zm%zw",
ckStr = (ddStr).split("%");
if (str.length > 5 && (
/^\w+([\.\-\'\+]?\w+)*#\w+([\.\-]?\w+)*(\.\w+)+$/i).test(str)) {
for (var i = 0; i < ckStr.length; i++) {
if (str.substring(str.lastIndexOf(".") + 1) == ckStr[i]) {
val = true;
break;
}
}
}
}
return val
}
I really appreciate helping me sorting this or providing any references.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So i have a html page with a guess my word game. but when i enter my first if statement with the variable FinalGuess for the indexOf it breaks, where as where i use SecretWord the page works but the function doesnt. any ideas?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" >
/* <![CDATA[ */
var SecretWord = "compaq";
var GuessInput = document.forms[0].Guess.text;
var FinalGuess = GuessInput.toLowerCase();
var firstLetter = false;
var b = false;
var c = false;
var d = false;
var e = false;
var f = false;
function checkLetter() {
if (SecretWord.indexOf('c') >= 0) {
firstLetter == true;
}
/*
if (userInput.indexOf('o') >= 0) {
b == true;
}
if (userInput.indexOf('m') >= 0) {
c == true;
}
if (userInput.indexOf('p') >= 0) {
d == true;
}
if (userInput.indexOf('a') >= 0) {
e == true;
}
if (userInput.indexOf('q') >= 0) {
d == true;
}
*/
if (firstLetter == false) {
var letter1 = "*";
} else {
var letter1 = "c";
}
if (b == false) {
var letter2 = "*";
} else {
var letter2 = "o";
}
if (c == false) {
var letter3 = "*";
} else {
var letter3 = "m";
}
if (d == false) {
var letter4 = "*";
} else {
var letter4 = "p";
}
if (e == false) {
var letter5 = "*";
} else {
var letter5 = "a";
}
if (f == false) {
var letter6 = "*";
} else {
var letter6 = "q";
}
var string = letter1 + letter2 + letter3 + letter4 + letter5 + letter6;
document.forms[0].word.value = string;
document.forms[0].Guess.value = "";
document.forms[0].Guess.focus;
alert(GuessInput);
}
/* ]]> */
</script>
</head>
<body onload="checkLetter();">
<form action="" >
Guess the word
<input type="text" name="word" id="word" /><br />
Enter text here
<input type="text" name="Guess" maxlength="1" />
<input type="button" name="Submit" value="Submit" onclick="checkLetter();" />
</form>
</body>
</html>
You have to replace :
firstLetter == true;
By :
firstLetter = true;
We use == for comparison, but when you want just to assign value use =.
<div id="form">
<form method="post" action="register1.aspx" onsubmit="return validateForm();"name="register1" >
<h1>
Register to exess the site</h1>
<input type="text" name="firstname" class=" br"/>
<em>First name</em><br />
<span id="firstnmsg"></span><br />
<input type="text" name="lastname" class=" br" /><em>Last name</em><br />
<span id="lastnmsg"></span><br />
<input type="text" name="username" class=" br" /><em>username</em><br>
<span id="usermsg"></span><br />
<input type="password" name="password" class=" br" /><em>password</em><br />
<input type="password"name="password1" class=" br" /><em>Confirm password</em>
<span id="pass1msg"></span><br />
<input type="text" name="email" class=" br"/><em>Email!</em><br />
<span id="emailmsg"></span><br />
<select name="sex">
<option>Please select a Gender</option>
<option>Male</option>
<option>Female</option>
<em>Gender</em>
</select><br />
<input type="submit" name="submit" value="Register " onclick="return validateForm();" />
<input type="reset" name="reset" value="Reset" onclick="return resetMsg();"/>
</form>
<span> <%=Session["regstatus"] %></span>
</div>
<div id="log_in">
<h1><em>log in</em></h1>
<form action="WebForm2.aspx"method="post" name="log_in" onsubmit="return validateloginform"><br />
<span id="usernamemsg"><%=Session["usernamemsg"] %> </span><input type="text" name="username_1" class="br" /><em>Username</em><br />
<span id="passwordmsg"><%=Session ["passwordmsg"] %></span><input type="password" name="password_1" class="br" /><em>Password</em><br />
<input type="submit" name="submit2" onclick=" validateloginform"/>
</form>
</div>
<script type="text/javascript">
function isEmpty(str) {
return (str.length == 0);
}
function isNumeric(str) {
var c = true;
for (var i = 0; i < str.length; i++) {
c = !(isNaN(str[i]));
}
return c;
}
function isValid(str) {
var badChar = "\\;:!##$%^&*()-_=+`~<>?[]{}|/,.";
for (var l = 0; l < str.length; l++) {
for (var c = 0; c < badChar.length; c++) {
if (str[l] == badChar[c]) {
return true;
}
if (str[l] == " " || str[l] == "\"" || str[l] == "\'") {
return true;
}
}
}
return false;
}
function isShort(str) {
return (str.length < 3);
}
//Reset Error Messages Function -->
function resetMsg() {
document.getElementById("firstnmsg").innerHTML = "";
document.getElementById("lastnmsg").innerHTML = "";
document.getElementById("usermsg").innerHTML = "";
document.getElementById("passwordmsg").innerHTML = "";
document.getElementById("pssword1msg").innerHTML = "";
document.getElementById("emailmsg").innerHTML = "";
document.getElementById("BdateMsg").innerHTML = "";
document.getElementById("UnameMsg").innerHTML = "";
document.getElementById("PwdMsg").innerHTML = "";
document.getElementById("LoginError").innerHTML = "";
return true;
}
//Main Sign Up Form Validation Function -->
function validateForm() {
resetMsg();
var val = true;
//First Name Validation ---------------------------------------->
if (isEmpty(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.firstname.value) || isValid(signup.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Last Name Validation ------------------>
if (isEmpty(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.lastname.value) || isValid(signup.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Username Validation --------------------------------------------->
if (isEmpty(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Empty";
val = false;
}
else {
if (!isNumeric(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Use Numbers";
}
else {
if (isShort(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Too Short";
val = false;
}
}
}
//Password Validation ----------------------------------------------->
if (isEmpty(register1.password1.value)) {
document.getElementById("Password1Msg").innerHTML = " Empty";
val = false;
}
else {
if (isValid(register1.password.value)) {
document.getElementById("Password1Msg").innerHTML = " Invalid";
}
else {
if (register1.password.value == register1.password1.value) {
if (signup.password1.value.length < 6 && signup.password1.value != "") {
document.getElementById("pass1msg").innerHTML = " Too Short";
val = false;
}
}
else {
document.getElementById("pass1msg").innerHTML = " Don't Match";
val = false;
}
}
}
//Email Validation -------------------------------------->
var EmailField = document.forms["register1"]["email"].value;
var atpos = EmailField.indexOf("#");
var dotpos = EmailField.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EmailField.length) {
document.getElementById("emailmsg").innerHTML = " Invalid Email";
val = false;
}
if (EmailField == null || EmailField == "") {
document.getElementById("emailmsg").innerHTML = " Empty";
val = false;
}
//Main Login Validation Function -->
function validateLoginForm() {
resetMsg();
var val = true;
//Username Validation
if (isEmpty(log_in.username.value)) {
document.getElementById("usernamemsg").innerHTML = " Empty";
val = false;
}
//Password Validation
if (isEmpty(log_in.password.value)) {
document.getElementById("passwordmsg").innerHTML = " Empty";
val = false;
}
return val;
}
</script>
The validations won't work and I dont know why. This is a school project.
my main problem is that the script isnt running when im submiting the form ,when there even some errors at the form(what the user submits) it still goes to the next page and no innerHtml massage is shown.
Here, I went through your code, refractored a lot of it, wrote out some comments on how to improve it.
What stops the form from submitting is returning false. You're returning a variable called val, and if there is an error that variable is set to false, thus returning false and preventing the form from submitting.
I recommend taking the JS and putting it in your text editor and reading through everything. You should learn a good bit.
Here it is: http://jsfiddle.net/2x5LU/
I just did first name cause I have to work now, but you should be able to work off of this.
function validateForm(){
resetMsg();
var val = true;
if(isEmpty(firstName.value)){
firstNameMsg = 'Empty';
val = false;
}else if(isNumeric(firstName.value)){
firstNameMsg = 'Letters Only';
val = false;
}else if(isShort(firstName.value)){
firstNameMsg = 'Too Short';
val = false;
}
return val;
}
Am a new JavaScript programmer and am trying to make a form validator using JavaScript but the error messages don't seem to be displaying if all the forms are not filled, that is if all are empty, only the name form error displays.
This is what I tried:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
if (x == "null" || x == "") {
var b = document.getElementById("nameErr");
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
var b = document.getElementById("nameErr");
b.innerHTML = "";
return true;
}
if (y == "null" || y == "") {
var c = document.getElementById("countryErr");
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
var c = document.getElementById("countryErr");
c.innerHTML = "";
return true;
}
if (z == "null" || z == "") {
var d = document.getElementById("occupationErr");
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
var d = document.getElementById("occupationErr");
d.innerHTML = "";
return true;
}
if (a == "null" || a == "") {
var e = document.getElementById("statusErr");
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
var e = document.getElementById("statusErr");
e.innerHTML = "";
return true;
}
}
This is the JavaScript code.
<form action="process.php" method="post" onsubmit="return myValidate()" name="myform">
Name:
<input type="text" id="name" name="name">
<span id="nameErr"></span><br><br>
Country:
<input type="text" id="country" name="country">
<span id="countryErr"></span><br><br>
Occupation:
<input type="text" id="occupation" name="occupation">
<span id="occupationErr"></span><br><br>
Status:
<input type="text" id="status" name="status">
<span id="statusErr"></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the HTML form.
Please help, Thanks
It seems you don't realize that calling return ends the function you are in. If the validation fails, you'll want to return false, but you do not want to return true until the end of the validation process.
Try:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
var b = document.getElementById("nameErr");
var c = document.getElementById("countryErr");
var d = document.getElementById("occupationErr");
var e = document.getElementById("statusErr");
if (!x || x.length==0) {
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
b.innerHTML = "";
}
if (!y || y.length==0) {
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
c.innerHTML = "";
}
if (!z || z.length==0) {
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
d.innerHTML = "";
}
if (!a || a.length==0) {
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
e.innerHTML = "";
}
return true;
}
This will return the first error it comes across. If you want to check them all at once, you will need to store your true/false in a variable and hold off on any return calls until then end and call return theVariableName;
you can use a flag for save state :
http://jsfiddle.net/vEvT2/1/
var flag = true;
and change to false if find empty control