Javascript: Where do i add the redirection? - javascript

I just need my form to redirect the user to another page after validation using javascript.
Here is my code:
function checkEnq() {
var x = document.forms["enq"]["email"].value;
var y = document.forms["enq"]["dB"].value;
var z = document.forms["enq"]["textF"].value;
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
}
}
How do i add the location.href or window.open once the js has checked that all fields (email, dB,& textF) are filled?
i can add target="_blank" action="./result.html" to the <form> field and it will still redirect to the result page even if the form is not filled up completely.

Add a "else" block
function checkEnq() {
var x = null;
var y = null;
var z = null;
try {
x = document.forms["enq"]["email"].value;
y = document.forms["enq"]["dB"].value;
z = document.forms["enq"]["textF"].value;
} catch(e) {
alert('code error');
};
if (x == null || x == "" || y == null || z == null || z == "") {
alert("Please make sure all fields are entered.");
} else {
document.location.href="/redirect.page"
}
}

I solved it by using this window.open("./page.html") instead of document.location.href

Related

Toogle between multiple variables does not work?

I want a toggle between font style. For example: If fontstyle does not exist in an element or if it is italic or oblique to insert normal, if it is normal to remove fontstyle after clicking on normal button.
I tried to solve this by inserting more variables in if (a || b|| c), but it doesn't work? Is this the correct way and is this possible or am I wrong somewhere in the code?
<div id="fontstyle">font-style</div>
<button onclick="ElementTextStyleNormal()">Normal</button>
<button onclick="ElementTextItalic()">Italic</button>
<button onclick="ElementTextOblique()">Oblique</button>
function ElementTextStyleNormal(){
var x = document.getElementById("fontstyle").style.fontStyle;
if (!(x == "" || x == "italic" || x == "oblique")) {
document.getElementById("fontstyle").style.fontStyle = "normal";
}
else if (x == "normal") {
document.getElementById("fontstyle").style.fontStyle = "";
}
}
function ElementTextItalic(){
var x = document.getElementById("fontstyle").style.fontStyle;
if (!((x == '') || (x == 'normal') || (x == 'oblique'))) {
document.getElementById("fontstyle").style.fontStyle = "italic";
}
else if (x == "italic") {
document.getElementById("fontstyle").style.fontStyle = "";
}
}
function ElementTextOblique(){
var x = document.getElementById("fontstyle").style.fontStyle;
if (!((x == '') || (x == 'normal') || (x == 'italic'))) {
document.getElementById("fontstyle").style.fontStyle = "oblique";
}
else if (x == "oblique") {
document.getElementById("fontstyle").style.fontStyle = "";
}
}
Try to simplify this by using a single function and the passing in the styleName as function parameter.
function ElementTextStyle(styleName){
var elem = document.getElementById("fontstyle");
elem.style.fontStyle = elem.style.fontStyle === styleName ? "" : styleName;
}
<div id="fontstyle">font-style</div>
<button onclick="ElementTextStyle('normal')">Normal</button>
<button name="italic" onclick="ElementTextStyle('italic')">Italic</button>
<button name="oblique" onclick="ElementTextStyle('oblique')">Oblique</button>

HTML Form won't submit after validaiton with Javascript

I have questions regarding form submitting in HTML with Javascript.
My Javascript is as follows:
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
alert("Your name cannot be blank");
}
if (b == null || b == "") {
alert("Enter a valid email address.");
}
if (c == null || c == "") {
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
alert("Must select an Issue.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (f == null || f == "") {
alert("Must fill in a description.");
}
if (g == null || g == "") {
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
alert("Preferred time must follow the format set.");
}
return false;
}
And this is my form with its attributes in HTML:
<form name="myForm" onsubmit="return validateForm()" method="post" action="confirm.html" novalidate="novalidate" >
What happens is that when I click the Submit button after filling in all the requirements(so everything does not return false) , the form won't submit itself.
After reading around regarding return false, I tried adding else{ return true; } but all it does is submit my form without validation at all.
What do I do to make it work with only Javascript and/or HTML? Thank you!
At the end of the submission function, you are returning:
return false;
}
No matter if the validation was successful or not. This prevents the form from submitting. Make sure you are using return true here and correctly validate using a flag and then if the flag is true, return false.
You have already a flag isValid. Replace the above line with:
return isValid;
}
You need to check if your inputs have passed your tests.
You can do that by using your var isValid.
All you need to do is set isValid to false if one of your conditions was not met, and then return isValid.
function validateForm() {
var a= document.forms["myForm"]["pname"].value;
var b = document.forms["myForm"]["pemail"].value;
var c = document.forms["myForm"]["pdob"].value;
var d = document.forms["myForm"]["unit of choice"].value;
var els = document.forms["myForm"].elements["Issue[]"];
var f = document.forms["myForm"]["description"].value;
var g = document.forms["myForm"]["pdatee"].value;
var h = document.forms["myForm"]["ptimee"].value;
var isValid = false;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
if (a == null || a == "") {
isValid=false;
alert("Your name cannot be blank");
}
if (b == null || b == "") {
isValid=false;
alert("Enter a valid email address.");
}
if (c == null || c == "") {
isValid=false;
alert("Enter a valid Date of Birth. (dd/mm/yyyy)");
}
if (d == null || d == "") {
isValid=false;
alert("Unit and Tutor have to be selected.");
}
if (!isValid) {
isValid=false;
alert("Must select an Issue.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (f == null || f == "") {
isValid=false;
alert("Must fill in a description.");
}
if (g == null || g == "") {
isValid=false;
alert("Preferred date must follow the format set.");
}
if (h == null || h == "") {
isValid=false;
alert("Preferred time must follow the format set.");
}
return isValid;
}

Arithmetic operations using Jquery

I have 3 textboxes,2 is for input value and 3rd is for operand,based on operand input it should perform relevant operation.
HTML
Num1:<input type="text" value=0 id="first" class="box1"><br>
Num2:<input type="text" value=0 id="second" class="box2"><br>
Op:<input type="text" value="+" id="oper" class="box3"><br>
<p id="demo"><b>Sum:0.00</b></p>
Onload of a document focus should be on first textbox,Validation of required fields should be done and the result should be fixed to 2 decimal places.
Jquery
$(document).ready(function () {
$("#demo").focus();
var x = parseInt($('#first').val());
var y = parseInt($('#second').val());
var z = $('#oper').val();
$("#first,#second,#oper").onkeyup(function () {
switch (z) {
case ("+"):
var a = ((x + y).toFixed(2));
$('#demo').text("Sum:" + a);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Sum:Enter a valid number!");
}
break;
case ("-"):
var b = ((x - y).toFixed(2));
$('#demo').text("Sub:" + b);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Sub:Enter a valid number!");
}
break;
case ("*"):
var c = ((x * y).toFixed(2));
$('#demo').text("Mul:" + c);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Mul:Enter a valid number!");
}
break;
case ("/"):
var d = ((x / y).toFixed(2));
$('#demo').text("Div:" + d);
if ((isNaN(x) || x == "") && (isNaN(y) || y == "")) {
$('#demo').text("Div:Enter a valid number!");
}
break;
default:
$('#demo').text("Invalid operator");
}
});
});
Trying to fix out the errors,please anyone can help me!!
As Tushar said, the event is handled using keyup, not onkeyup.
You need to move the variable assignments into the keyup handler, as you want them to be re-calculated every time they change.
$(document).ready(function () {
$("#first").focus();
$("#first,#second,#oper").keyup(function () {
var x = parseInt($('#first').val());
var y = parseInt($('#second').val());
var z = $('#oper').val();
switch (z) {
....
To focus on the first textbox, you want to focus on the first textbox id, rather than the p tag.
$("#first").focus();
This will then work like you expect.
I have fixed this issue you can check on js fiddle please tell me if you have any issue.
link here -- http://jsfiddle.net/FHf9a/317/

Javascript validate empty fields

Can anyone help me on how to validate the javascript form if the
following fields are empty? It doesn't seem to work for my code.
function addvalidation(){
var w = document.forms["shop"]["w"].value;
var t = document.forms["shop"]["t"].value;
var a = document.forms["shop"]["a"].value;
var c = document.forms["shop"]["c"].value;
var s = document.forms["shop"]["s"].value;
var c = document.forms["shop"]["c"].value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}
http://jsfiddle.net/tn2fvh4p/91/
http://jsfiddle.net/tn2fvh4p/68/
Please use following code
function addvalidation(){
var w = document.getElementById("w").value;
var t = document.getElementById("t").value;
var a = document.getElementById("a").value;
var c = document.getElementById("c").value;
var s = document.getElementById("s").value;
var c = document.getElementById("c").value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}

How to combine two if statements into one?

I know there is a much cleanlier way to write this than multiple if statements but when I try to combine them my validation stops working! This isn't good practice right? Or in this case is two different if statements okay?
My code:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
}
var x = document.forms["contestForm"]["lastName"].value;
if (x == null || x == "") {
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#lastNamespan'), 'formError');
}
return success;
}
My attempt to combine:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName", "lastName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan', '#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan', '#lastNamespan'), 'formError');
}
return success;
}
So what am I doing wrong? I also will need to add a birthday and e-mail validation but I wanted to get this cleaned up first before it became a monster of if else statements! Sorry for the extra non-helpful information its making me write more because I have to much code. Please feel free to edit and delete this once its posted.
Combine them by functional programming:
function validateForm() {
var x = document.forms["contestForm"]["firstName"].value;
//calls the function checkObject with the object x and the id
var success1 = checkObject(x, '#firstNamespan');
//the result of success1 is either true or false.
var x = document.forms["contestForm"]["lastName"].value;
//calls the function checkObject with the object x and the id
var success2 = checkObject(x, '#lastNamespan');
//the result of success2 is either true or false.
//returns true if both success1 and success2 are true, otherwise returns false.
return success1 && success2;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Which could then be condensed into
function validateForm() {
return checkObject($('form[name="frmSave"] #firstName').val(), '#firstNamespan') && checkObject($('form[name="frmSave"] #lastName').val(), '#lastNamespan');
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Answer for N number of fields with your pattern of naming
function validateForm() {
var itemsToValidate = ["#firstName", "#lastName", "#birthday", "#email"];
var results = [];
$.map( itemsToValidate, function( val, i ) {
results.push(checkObject($('form[name="frmSave"] ' + val).val(), val + 'span'));
});
for(var i=0; i<results.length; i++)
{
if(results[i] == false)
return false;
}
return true;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Note: I didn't validate any of the JavaScript above please call me out if i made a mistake. I just typed this up in notepad as i'm out the door at work
Break things up into functions and utilize an array to loop through the fields to validate.
function isValidField(fieldName) {
var value = document.forms["contestForm"][fieldName].value;
return !(value == null || value == "");
}
function displayFieldError(fieldName) {
addClass($('#' + fieldName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
}
var fields = ['firstName', 'lastName'];
var isValidForm = true;
fields.map(function(fieldName) {
if (!isValidField(fieldName)) {
displayFieldError(fieldName);
isValidForm = false;
}
});
if (isValidForm) {
// Form is correct, do something.
}
By giving them a seperate identifier like this
var x = document.forms["contestForm"]["firstName"].value;
var y = document.forms["contestForm"]["lastName"].value;
if ((x == null || x == "") && (y == null || y == "")) {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
removeClass($('#lastNamespan'), 'formError');
}
But you need to be more precise about, what would you do with just addClass? That won't work. You need have a JS object before this method call.
I think, you want some element there before the addClass and removeClass. Or they need to be like this
$('#firstNamespan').removeClass('formError');
Like this, you need to change your code. So that the object comes first and then the method call.
Make it a function,
function validateForm(formName) {
var x = document.forms["contestForm"][formName].value;
if (x == null || x == "") {
addClass($('#' + formName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
}
removeClass($('#' + formName + 'span'), 'formError');
addClass($('.validationError'), 'is-hidden');
return true;
}
then you can call it twice,
function validateForm() {
var success = validateForm('firstName');
if (success) {
success = validateForm('lastName');
}
return success;
}
The two ifs are checking two different form elements, and showing and hiding two different validation error elements.
Combining them will not be just a code refactor but also change functionality.
The only thing they have in common are that they both use the same variable 'x'.

Categories

Resources