I'm writing javascript to validate a business calculator / orderform
another team mate has written the math code, but when I put in my code the whole thing stops.
I can't find my error (I'm more a css/html person)
help?
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
var orderdetailsarray = new Array();
//validation//
// these are boolean variables that when made true//
//by the validation will allow the calculation and logging to occur//
var clientnamevalid = new Boolean(false);
//Regex Variables//
//these are the regex patterns that are used to //
//confirm that the data is valid//
var alpha = pattern=/^[a-zA-Z\-]+$/;
function validation()
{
function validation();
{console.log (clientname);
if(alpha.test(clientname));
var clientnamevalid = true;
if { clientnamevalid = true;
alert(client name valid); //to be replaced with inline alert
}
else {
alert("client name invalid");
}
}
Edit Updated code:
the vars are now
var clientname =document.getElementById('clientname');
the function:
function validation()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid')
}
else
{
alert("client name invalid");
}
}
Edit Updated code 2:
<button name="calculate" id="calcbutton" onclick="validate()"> Calculate </button>
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
if clientnamevalid = true;
{
function calculateorder();
}
}
edit 3:
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid"); //edited from single quotations
}
else
{
alert("client name invalid");
}
if (clientnamevalid == true);
{
calculateorder();
}
else
{
alert ("please review form");
}
}
calc order func:
function calculateorder()
{
orderdetailsarray [0] = document.forms["orderform1"] ["clientname"].value;
orderdetailsarray [1] = document.forms["orderform1"] ["phoneno"].value ;
orderdetailsarray [2] = document.forms["orderform1"] ["deliveryaddress"].value;
orderdetailsarray [3] = document.forms["orderform1"] ["suburb"].value;
orderdetailsarray [4] = document.forms["orderform1"] ["postcode"].value;
orderdetailsarray [6] = parseFloat(document.forms["orderform1"] ["deldistance"].value);
orderdetailsarray [7] = parseFloat(document.forms["orderform1"] ["bagsordered"].value);
orderdetailsarray [8] = document.forms["orderform1"] ["orderdate"].value;
//gross calculation
var grossbagcost = orderdetailsarray[7] * millendcost;
grossbagcost = Math.round(grossbagcost *100)/100;
document.forms["resultsform"] ["bagsgross"].value = grossbagcost;
//end gross calculation
//discount amount calculation
if (orderdetailsarray [7] <=50)
{
var discountedbagcost = grossbagcost * discountnil;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >50 && orderdetailsarray[7] <100)
{
var discountedbagcost = grossbagcost * discount4percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >=100)
{
var discountedbagcost = grossbagcost * discount7percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
updated code with null check
function validate()
{console.log (clientname);
//pattern test
var clientnamevalid == alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid");
}
else
{
alert("client name invalid");
//null check
}
if (x==null || x=="")
{
alert("Client name cannot be left blank");
clientnamenotnull == false;
}
else
{
clientnamenotnull == true;
}
//is the whole form valid
{
if (clientnamevalid == true)
if (clientnamenotnull) == true)
{
calculateorder();
}
else
{
alert ("please review form");
}
}
This appears to be problem area:
function validation()
{
function validation();
You have function inside another function.
Your function validation() is one big bug.
Did you mean
function validation(clientname)
{
console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if (clientnamevalid)
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
}
And you don't call that function in your code. And remember, parentheses and curly braces position does matter.
Another one, adding to anubhava's answer you need to change all getElementById from
document.getElementById(deldistance);
to
document.getElementById('deldistance');
In addition to anubhava and Surender,
the document.getElementById() get string.. so you need to change all this
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
and write the parameters between quotes.
for example:
var bagsordered = document.getElementById('bagsordered');
because as you wrote it, it confuse the compiler.
you can't pass the variable you just declare now at the same line you want his id.
if you're a css/html person as you say, you know that when you create an html button or div
you can define his id.
like <input type="button" id="order" value="press to order" />
now in javascript you can add functionality to this button. so when you want to get
this button in javaScript you can use the function document.getElementById('order')
see? I gave the id of the button that was declared in the html code.
hope you understand what i mean
Edit
look, when you have a button, as you said. for example i'll use the button I wrote before.
<input type ="button" id="order" value="press to order"/>
now if I have a function called "function()";
and I want that when the user will press on the button the function will be called
so I'll add to the html code of the button the onclick
so now it will be :
<input type = "button" id="order" value ="press to order" onclick="function()"/>
now when the user will click on that button, the function will be called and the code in it will performed
in addition, when you write a function that will change some label or button text.
you will need to get theirs id.
if my function is "changeText()". and I have a button with value "Hello" and id = "btn"
and I want to change the button value's from "Hello" to "wow"
so I need to get that button right?
and how do I get it?
with the method document.getElementById
here is the code:
function changeText()
{
var btn = document.getElementById('btn');
btn.value = "wow";
}
Edit 2:
clientnamevalid is boolean,right?
so when you want to check if it true or false, you can use the if statement.
if (clientnamevalid == true)
{
// do something, like call to calculateorder
calculateorder();
}
else // it's false
{
// do something else
}
note that you don't have to compare the 'clientnamevalid' variable or all another boolean variable to 'true' or 'false', the if statement does it alone. so you can write
if (clientnamevalid) // means that the clientnamevalid is true
{
calculateorder();
}
else
{
// do something else
}
Edit 3:
** From where you get the client name?! you need to enable the user to enter his name..
So you need a Form.. **
function validate()
{
console.log (clientname);
if (clientname != "" || clientname != null)
{
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid)
{
alert("client name valid");
calculateorder();
}
else
{
alert("client name invalid, please review form");
}
}
else
{
alert("client name can't be empty!");
}
}
Related
I am trying to work on verifying OTP. Here I have two components that are:
Textbox which takes input of OTP. id="txtOTP"
An Status Line (here i have used <i> tag) that shows status of verified OTP. id="statusLine"
I am using JavaScript for this purpose.
function checkOTP()
{
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP.value == myOTP)
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if (OTP.value != myOTP)
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
As Per my code it should go to the if's scope if OTP is correct, and it should go to the else's scope if OTP is wrong.
However, it always goes to the else's scope even though I am writing the correct OTP in the textbox. I have even tried this code without using if with the else statement (like else if() { } ).
You need to either change myOTP to a number or use double equals:
var myOTP = parseInt(txtOTP.value);
Or:
if (OTP == myOTP) {...}
Also note that you don't need else if (...) - just use else {...}.
OTP is a Number but you check OTP.value in if/else if statements
function checkOTP()
{
var OTP = 1234;
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if(OTP === myOTP )
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if(OTP != myOTP )
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
Here is a solution. Its based on the comments and previous answers:
function checkOTP() {
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP == myOTP) {
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
} else {
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
You needed to write OTP instead of OTP.value and you don't need and else if for the opposite. Just else will do.
try adding a else statement after the else if since the syntax is :
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.
I've javascript confirmation function like this:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your team is incomplete. Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I want to show this when the team really incomplete. I check it in save button click. If false; I want to call JS confirm function:
if ((teamList.Contains("Purchasing") && teamList.Contains("Quality") && teamList.Contains("Process") && teamList.Contains("R&D")))
{ }
else
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CallMyFunction", "Confirm()", true);
}
If confirm returns yes, I want to save them. If no, I don't want to save them.
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Do save operations
}
These code snippets returns null first time, and it returns my confirm answer (yes or no) when the other button clicks.
How can I do?
I' working on a PHP-Jquery-Ajax submit info form and I would like to use the addclass and removeclass jquery methods but I can't make it work as I want, so my question is: How do I have to fix the code below in order to add a css depending on the user input?
The addclass and removeclass are in the function verificaForm where I validate the input fields, in this case I only show you two fields validations but there are more... I also know that out there is a library(validate.js) that helps to validate the inputs from users but in this specific case I must have to sitck to this code.
here is my js code and thanks in advance:
$(document).ready(function () {
$('#ID_formulario').on('submit', function (e) {
e.preventDefault();
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
$('#result').html("<b>resolviendo peticion...</b>");
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
//...more code goes here ... it works fine ...
}
});
});
function validaForm(nombre, email) {
if ((nombre == '') || nombre.replace(/s+/, '') == '') {
alert("Favor especificar nombre");
nombre.addClass('hightlight');
return false;
} else {
else nombre.removeClass('hightlight');
}
if (nombre.length < 4) {
alert('El valor del campo es muy corto');
return false;
}
if ((email == '') || email.replace(/s+/, '') == '') {
alert("Favor especificar correo");
return false;
}
return true;
}
You should pass the element to the function, not the value. Then You can obtain the value within the function. Something like that:
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email))
....
function validaForm(nombre,email){
var nombre_value = nombre.val().trim();
var email_value = email.val().trim();
.......
So, you can add classes to a jQuery object and not to a value. Change things around like below.
Replace
var nombre = $('input#ID_nombre').val().trim();
var email = $('input#ID_email').val().trim();
if (validaForm(nombre, email)) {
With
if (validaForm($('input#ID_nombre'), $('input#ID_email'))) {
And modify your function as below.
function validaForm(nombre,email) {
var nombreVal = $.trim(nombre.val());
var emailVal = $.trim(email.val());
if ((nombreVal == '') || nombreVal.replace(/s+/, '') == '') {
..........
..........
}
And remove that extra else in here:
} else {
else nombre.removeClass('hightlight');
}
And change it to
} else {
nombre.removeClass('hightlight');
}
I've got some code for a Javascript alert. I want my client to be able to enter a code to access an area of my website.
At the moment I have some JS code that if a user enters the wrong credentials an alert box is created and a user selects okay and it goes to the website anyway. This is not ideal.
How can I have a loop that re-creates the prompt box until the correct credential (variable x) is supplied.
window.onload = function launch() {
var x = "name of credential";
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
<?php header("Location : index.php");?>
}
else {
alert("You have entered the wrong credentials please try again!");
var person = prompt("The Care Socierty website is under development\nPlease enter your development code:");
}
Krishna's suggestion
window.onload = function launch() {
var x = "credential";
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
window.location;
}
else {
alert("You have entered the wrong credentials please try again!");
return false;
}
}
Make a loop in order to iterate you code
Try this one it might help you
window.onload = function () {
var x = "name of credential";
var wrong = true;
while (wrong) {
var person = prompt("The website is under development\nPlease enter your development code:");
if (person == x) {
alert("Success!");
wrong = false;
<?php header("Location : index.php");?>
}
}
}
Just try with:
if (person == x) {
alert("Success!");
window.location = 'index.php';
} // ...
If you need to keeps prompting you need to do something like this.
Try here : http://jsbin.com/duroguji/2/edit
$(function () {
setTimeout(askPermission,1000);
});
function askPermission()
{
var success = false;
var x = "HELLO";
while(!success)
{
var person = prompt("The website is under development\nPlease enter your development code:", "");
if (person == x) {
success = true;
alert("Success!");
}
else {
alert("You have entered the wrong credentials please try again!");
setTimeout(askPermission,1000);
}
}
}