Validate and display window alert - javascript

how do I validate to ensure a value for total or orderForm have been fill up if not it will display a window alert upon clicking on Submit button ?
It seems the below is not working at all .
Pure JS:
function va(){
var result = false;
var w = document.forms["orderForm"]["companyName"].value;
var x = document.forms["orderForm"]["forename"].value;
var y = document.forms["orderForm"]["surname"].value;
var z = document.forms["orderForm"]["total"].value;
if (x == null || x == "") && (y == null || y == "") && (w == null || w == ""){
window.alert('Name must be Filled out');
result = false;
// } else if (z = < 5){
// window.alert('Please Select A CD');
// return false;
// }else {
// return true;
}
return result;
}
HTML:
<section id="checkCost">
<h3>Total cost</h3>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
<section id="placeOrder">
<h3>Place order</h3>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>

try this:
if (x == null || x == "") {
window.alert('forename must be Filled out');
result = false;
} else if (y == null || y == "") {
window.alert('surname must be Filled out');
result = false;
} else if (w == null || w == "") {
window.alert('companyName must be Filled out');
result = false;
}
return result;

Try:
if ((x == null || x == "") || (y == null || y == "") || (w == null || w == ""))
EDIT:
Sure thing, original line:
if (x == null || x == "") && (y == null || y == "") && (w == null || w == "")
I did two things. Switch out the && for || and wrap the if condition in an inclusive set of parenthesis (which probably isn't required but I do it for neatness). The original if statement reads as "if condition and condition and condition" meaning all conditions have to return true (i.e. be blank) in order to continue. I believe each of these values are required to validate the form. My proposed if statement would read "if condition or condition or condition" letting the alert box be displayed if any value is empty.

Related

Javascript conditional statements with range input values

could someone help me with the following Javascript code. I want the conditional statements to execute if the value of "score" is between the ranges of 1-3, 3-5, 5-7, 7-9 and 9-10.
Currently, they only execute if the variable "score" is an integer, but I want the scores to be executed between the range of numbers.
for example, I want the line "if ((score==1) || (score==2) || (score==3))" to be something like if( score is between 1 and 3), Then the statement will be executed.
This is the HTML:
Input 1 <input type="number" id="num1">
<br>
<br>
Input 2 <input type="number" id="num2">
<br>
<br>
Input 3 <input type="number" id="num3">
<br>
<br>
Input 4 <input type="number" id="num4">
<br>
<br>
Input 5 <input type="number" id="num5">
<br>
<br>
<button onclick="calculate()">Calculate</button>
<h1 id="answer"></h1>
<h1 id="advice"></h1>
This is the JS:
function calculate()
{
var field1=document.getElementById("num1").value;
var field2=document.getElementById("num2").value;
var field3=document.getElementById("num3").value;
var field4=document.getElementById("num4").value;
var field5=document.getElementById("num5").value;
if ( (field1>10) || (field1<1)|| (field2>10) || (field2<1) || (field3>10) || (field3<1) || (field4>10) || (field4<1) || (field5>10) || (field5<1))
{
alert("Enter a number between 1 and 10");
return false;
}
var result=parseFloat(field1)+parseFloat(field2)+parseFloat(field3)+parseFloat(field4)+parseFloat(field5);
var score= result / 5;
if ((score==1) || (score==2) || (score==3))
{
document.getElementById("advice").innerHTML="You are between 1 and 3";
}
if ((score==4) || (score==5))
{
document.getElementById("advice").innerHTML="You are between 4 and 5";
}
if ((score==6) || (score==7))
{
document.getElementById("advice").innerHTML="You are between 6 and 7";
}
if ((score==8) || (score==9))
{
document.getElementById("advice").innerHTML="You are between 8 and 9";
}
if ((score==10))
{
document.getElementById("advice").innerHTML="You are 10";
}
if(!isNaN(score))
{
document.getElementById("answer").innerHTML="Your career score is " + score;
}
}
Help will be super appreciated!
if (score >= 1 && score < 3) {
// do something
} else if (score >= 3 && score < 5) {
// do something
}
... and so on
Also I would like to help you write better code:
This:
if ( (field1>10) || (field1<1)|| (field2>10) || (field2<1) || (field3>10) || (field3<1) || (field4>10) || (field4<1) || (field5>10) || (field5<1))
{
alert("Enter a number between 1 and 10");
return false;
}
And more cleaner code:
const fault = [field1, field2, field3, field4, field5].find(el => {
if (el < 1 || el > 10) { // if we find this, then fault will be the index of this element
return true
} else { return false } // else fault will be undefined
})
if (fault) {
alert("Enter a number between 1 and 10")
return false
}

Trouble with JavaScript Validation on Form

I am Trying to validate some input for a login form using JavaScript. From what I can see, everything in the script is correct, but it is not working. I'm sure it's a tiny thing that I've missed, any help would be appreciated.
Note: I am unable to use external libraries.
JavaScript code:
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if (isNaN(x)) && (y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x)) && (y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true) && (y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
</script>
HTML Code:
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
(I'm very new to web dev, please don't judge too much :p)
In addition to other answers :
this line : var x = document.forms["login"]["username"].value; will store the value of username as a string, even if a numerical value is entered. Now I invite you to test the following line of code :
Number.isInteger('12')
It will return false.
One of the possible solutions would be to use parseInt on x before using it :
var x = parseInt(document.forms["login"]["username"].value);
It will still return NaN if a non int parsable value is given, and transform it to an int if the value is parsable.
Side Note :
parseInt('a') == NaN
parseInt('12') == 12
parseInt('12a') == 12
You were missing brackets around the conditions for if statements.
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ((isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ((isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ((Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
<form name="login" method="get">
<input type="text" placeholder="Customer ID" name="username">
<input type="password" placeholder="Password" name="password">
<input type="submit" onclick="return validateForm()" value="Log In" name="button">
<?php if (isset($errormessage)) { echo $errormessage; } ?>
</form>
Let me know if you have any questions.
<script>
function validateForm() {
var x = document.forms["login"]["username"].value;
var y = document.forms["login"]["password"].value;
if ( (isNaN(x)) && (y === "")) {
alert("Username must be numerical, and password must be entered!");
return false;
} else if ( (isNaN(x)) && (y !== "")) {
alert("Username must be numerical!");
return false;
} else if ( (Number.isInteger(x) == true) && (y === "")) {
alert("Password must be entered!");
return false;
} else {
return true;
}
}
You have missed some parentheisis in your script please use this code
You've got extra parentheses in your if statement:
if (isNaN(x))<- this is closing the conditional and is not required
Remove that and it should work:
if (isNaN(x) && y === "") {
The else branches also have this issue, the whole if should appear like this:
if (isNaN(x) && y === "") {
alert("Username must be numerical, and password must be entered!");
return false;
} else if (isNaN(x) && y !== "") {
alert("Username must be numerical!");
return false;
} else if (Number.isInteger(x) == true && y === "") {
alert("Password must be entered!");
return false;
} else {
return true;
}
Also, the isNan function can be used from Number (just like isInteger) instead of global, this would make script more consistent :)

Very strange javascript issue with booleans

Booleans will work before setting variables inside a function but not after? The variables are all taken from forms except "status".
Here is the function:
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function signup(){
// if(1==1){ -----When I place this here, the alert comes up.
// alert("yes");
// }
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
// Nothing below here works
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == "" || o == ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signupfront.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&a="+a+"&o="+o);
}
}
This function is called by a button, and I want the function to return the messages alongside the button.
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
main.js contains the following:
function _(x){
return document.getElementById(x);
}
Any help with this would be greatly appreciated as I have been looking at it for hours and cannot figure it out.
Thanks in advance
Here is the html as requested:
<body>
<div id="pageMiddle">
<h3>Create Account</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Age:</div>
<input id="age" type="text" onfocus="emptyElement('status')" maxlength="3">
<div>Occupation:</div>
<input id="occ" type="text" onfocus="emptyElement('status')" maxlength="88">
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
//long list of countries here
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Our Terms Of Use</h3>
<p>v</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
</body>
if any of your input fields that you are referencing in the variable declaration do not exist your code will fail, because you are calling .value on an undefined field.
post your HTML and we can figure it out.
Have a look at the gender input
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
Here's your mistake
var g = _("gender").value;
The code breaks at the above line because you're trying to get the value of an element with id equals gender, but there's no element with id="gender" attribute.
You need to change the gender input to the following, where the radio buttons have the unique id (genderMale and genderFemale)
<div>Gender:</div>
<input type="radio" name="gender" id="genderMale" value="m">Male
<input type="radio" name="gender" id="genderFemale" value="f">Female
then use the following syntax to assign the value of the selected gender to g variable
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
Below is the modified part of the javascript
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
if (u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == ""
|| o == "") {
status.innerHTML = "Fill out all of the form data";
alert("true");
}
Demo: http://jsfiddle.net/zpeu4fq9/1/
Try using this
if(1===1){
alert("yes");
}
if(u === "" || e === "" || p1 === "" || p2 === "" || c === "" || g === "" || a === "" || o === ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
Hope this help

Javascript Validation for Radio Buttons in a form with multiple Validations

I'm having trouble finding a way to validate my Gender choice action buttons. I've made efforts at doing it by saying that the buttons can't be left null, but it still recognises one button as being null and won't let me continue. I've tried different variations of this like saying both male and female aren't selected then return false but it still won't work for me. I'm beginning to think that the method I'm going about it just may not be correct. The main issue you want to look at the below is the two radio buttons but I have included the rest of the code as context for the Javascript. The rest of the code works fine it is only the radio buttons than I'm struggling with. Thanks.
Html
<form action="ReviewPHP.php" name="review" onsubmit="return validateForm()">
<fieldset>
Title: <input type="text" name="Title">
</br>
Email Address: <input type="text" name="Email">
<br/>
Rating: <select name="Rating">
<option value="0"></option>
<option value="1">Excellent</option>
<option value="2">Good</option>
<option value="3">Bad</option>
<option value="4">Awful</option>
</select>
<br/>
<textarea name ="Comments" rows="8" colspan="40">Comments:
</textarea>
<br/>
<input type="radio" name="Gender" id="male" value="male">Male
<input type="radio" name="Gender" id="female" value="female">Female
</fieldset>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
Javascript
function validateForm()
{ //Variable declarations for form inputs
var t = document.forms["review"]["Title"].value;
var e = document.forms["review"]["Email"].value;
var r = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var b = document.forms["review"]["Gender"].value;
var atsymb = e.indexOf("#");
var dotsymb = e.lastIndexOf(".");
if (t == null || t == "") {
document.getElementById("valAlert").innerHTML = "Title Missing";
return false;
}
else if (e == null || e == "" || atsymb < 1 || dotsymb < atsymb + 2 || dotsymb + 2 >= e.length)
{
document.getElementById("valAlert").innerHTML = "Email Missing";
return false;
}
else if (r == "0") {
document.getElementById("valAlert").innerHTML = "Please Rate the Movie, it's why you're here";
return false;
}
else if (c == null || c == "" || c.length < 10) {
document.getElementById("valAlert").innerHTML = "Reviews gotta be at least 10 characters!";
return false;
}
else if (b == null) {
document.getElementById("valAlert").innerHTML = "Please select Gender";
return false;
}
else {
alert("Review for " + t + " has been submitted, Good Job!");
return true;
}
}
You can use checked property to know if a option is checked.
document.getElementById('male').checked
The document is here:
http://www.w3schools.com/jsref/prop_radio_checked.asp
I guess what you would like to do is something like this:
var b = "";
if (document.getElementById('male').checked) {
b = document.getElementById('male').value;
}else if(document.getElementById('female').checked) {
b = document.getElementById('female').value;
}
if(b == "" | b == null ){
// alert
}
Hope this helps.
You have to check if b is undefined.
if (!b || b == null) {
I pared down the javascript and made a simple working demo:
http://jsfiddle.net/z7e7D/

Javascript validate form OR function

I am trying to ask the user to input at least 1 of the options. From my codes the user need to input all the inputs. Can anyone please check what is wrong with my code?
jsp
<form role="form" method="POST" id="search" action="Servlet"
onsubmit="return validateForm();">
<label>Name</label>
<input name="name">
<label>ID</label>
<input name="id">
<label>no</label>
<input name="no">
<button type="submit">Search</button>
</form>
javascript
function validateForm() {
var name = document.forms["search"]["name"].value;
var id = document.forms["search"]["id"].value;
var no = document.forms["search"]["no"].value;
if ( (name == null || name == "") || (id == null || id == "") || (no == null && no == "")) {
alert("Please enter either one to perform search");
return false;
}
}
Just a little logic adjustment should do the trick:
if (
(name != null || name != "") ||
(id != null || id != "") ||
(no != null && no != "")
) {
This is saying that if any one of the fields has a value, continue.
function validateForm() {
var name = document.forms["search"]["name"].value;
var id = document.forms["search"]["id"].value;
var no = document.forms["search"]["no"].value;
if ( (name == null || name == "") && (id == null || id == "") && (no == null || no == "")) {
alert("Please enter either one to perform search");
return false;
}
}
or you would do it as #isherwood did. also take care of typos like not closing your input tag
should goes like this <input name="no"/> good luck and I hope this would help

Categories