Adding function is disabling other functions in the js file - javascript

I had this function in a js file and everything was working just fine :
function check_acco_form()
{
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR must be all numbers
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Invalid dates.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
});
}
I made a little changes to this function (added the variables 'mobile_num' and 'train_num', included 'if' conditions to make sure the user enters numbers only and made changes to the jQuery get function) that which resulted in the following code:
function check_acco_form()
{
//Personal Information
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//Contact Information
var mobile_num=$("#mobile").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
//Train Number
var train_num=$("#trainnum").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty.
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR can be empty but if entered must be all numbers
if(pnr1!="" and pnr2!="")
{
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
}
//Train number can be empty but if entered must be all numbers
if(train_num!="")
{
if(!train_num.match(numericExpression))
{
alert("Train number must consits of digits only");
$("#trainnum").val("");
return;
}
}
//Mobile num can be empty but must be all numbers
if(mobile_num!="")
{
if(!mobile_num.match(numericExpression))
{
alert("Invalid mobile number");
$("#mobile_num").val("");
return;
}
if(mobile_num.length!=10)
{
alert('A mobile number consists of 10 digits.Please enter again.');
return;
}
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Departure date cannot be before arrival date.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date+"&mobile="+mobile_num+"&train_num="+train_num;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
$("#acco_letter_print").html('Download accomodation letter here');
$("#acco_letter_print").fadeIn();
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
}); //End of get function
}
After the changes, suddenly all functions in the js file of this function have stopped working including this function. On searching the forum , I found this discussion : JavaScript function causing all other functions not to work inside js file which says that the error may be due to use of reserved words. However , I can't find any reserved words used as variables in my code. Any ideas what may the problem?

You have this in there:
if(pnr1!="" and pnr2!="")
It should be:
if(pnr1!="" && pnr2!="")
Any syntactical errors like this will cause the entire thing to fail, be sure to check your error console for things like this, they'll quickly point out the cause.
As an aside, try not to pass a string to setTimeout() as well, pass the function reference directly, changing this:
setTimeout('fadeOutMsgBox();',3000);
To this:
setTimeout(fadeOutMsgBox,3000);
This will give less issues, and allow the function to be anywhere in scope, it doesn't have to be global (like it would with a string).

Related

How can I get my span id’s to display the appropriate messages when user doesn’t follow rules?

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});

JavaScript Cannot read property 'preventDefault' of null

I am checking the phoneNumber.length in my CRM form. So far I got the check between 8-15 character = acceptable to work. When I try to stack an 'if' to check for zero characters I get:
TypeError: Cannot read property 'preventDefault' of null at checkPhoneNumber
function checkPhoneNumber(executioncontext) {
var phoneNumber;
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
if (phoneNumber == null) {
Xrm.Page.ui.setFormNotification("Phonenumber can't be empty", "WARNING", "telephone1nc1");
Xrm.Page.getControl("telephone1").setFocus(true);
executioncontext.getEventArgs().preventDefault();
} else {
Xrm.Page.ui.clearFormNotification("telephone1nc1");
//Insert 8-15 characters
if (phoneNumber != null) {
if (phoneNumber.length < 8 || phoneNumber.length > 15) {
Xrm.Page.ui.setFormNotification("Phonenumber must be between 8-15 chars..", "ERROR", "telephoneerror1");
Xrm.Page.getControl("telephone1").setFocus(true);
} else {
if (phoneNumber == null) {
Xrm.Page.ui.setFormNotification("Telefonnummret får inte vara tomt", "WARNING", "telephone1nc1");
Xrm.Page.getControl("telephone1").setFocus(true);
//executioncontext.getEventArgs().preventDefault(); //vid 0 bombar scriptet
} else {
Xrm.Page.ui.clearFormNotification("telephone1nc1");
}
Xrm.Page.ui.clearFormNotification("telephoneerror1");
}
/*var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
if (regex.test(executionObj)) {
// Valid international phone number
} else {
// Invalid international phone number */
}
}
}
Once I get that sorted out I will start working on the code to check for international format and inserting the country code based on country of the entity. Hence the commented var regex.
You need to ensure executioncontext.getEventArgs() is not null.
Easiest way to do this in a single line:
executioncontext.getEventArgs() && executioncontext.getEventArgs().preventDefault();
executionContext.getEventArgs() for Dynamics CRM is only relevant for save-events:
This method returns null for any event other than the Save event.
It would appear that your code is not (only) running OnSave.
With that being said, the normal way of forcing users to fill out fields in Dynamics CRM is to make them Business Required (i.e. the fields get red asterisks, and users cannot save the form without filling the fields) - not to manually make form notifications.

ServiceNow Script onSubmit not working properly

I am using ServiceNow platform. I am writing a Catalog Client Script to validate form fields on a Catalog Item record producer.
I am stopping the submission of the form by using return false if validation does not pass inspection.
I have tested this by entering invalid data (group name with special characters or a group name that exists already) and it catches the issue and shows the error message. I can enter invalid data and submit multiple times and it works.
However, the issue:
The script seems to "stop" running after I first enter invalid data and submit, and then I correct the data press the submit button again. It just sits there and does nothing. I have to reload the form again which is not desirable.
What is going on with the control flow? How can I cleanly stop the form if the data is invalid, but then allow the user to correct the mistake and press the submit button again to proceed?
I can tell that the script doesn't run again because I have an alert box popping up that says "script run" every time the script runs. It just stops running at some point after submitting invalid data first and then entering some valid data and pressing submit.
function onSubmit() {
g_form.hideAllFieldMsgs('error');
alert("script run");
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
if (regGrpName.test(group_name) == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
//g_form.submitted = false;
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_google_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
// Hide error message
//g_form.hideErrorBox('u_group_members');
var group_members = g_form.getValue('u_group_members');
// Comma separate list
var member_split = group_members.split(',');
// Loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// Trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// Email validation regular expression
var regEmail = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// Check each item against regular expression
if (member_info.search(regEmail) == false) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
//Do not submit
//g_form.submitted = false;
return false;
} else if (member_info.search(validRegExp) == true) {
g_form.setValue('u_group_members', group_members);
}
}
return true;
}
I'm glad you found a solution above, but I wanted to leave a comment as well, to ask if you've tried a try{} catch{} block to handle invalid data?
I think I have solved the issue. I made a completely separate function that checks the validation. The onSubmit calls the validation function and checks the return value. If the return value is false then it stops the form. Otherwise it is submitted even after multiple attempts with invalid data. I think this will do the trick. Let me know if anyone can see any issues. Thanks for the help.
function onSubmit() {
var isValid = checkGoogleGroup();
if (isValid == false) {
g_form.submitted = false;
return false;
}
}
function checkGoogleGroup() {
g_form.hideAllFieldMsgs('error');
//Group Name contain letters numbers and dashes only
var group_name = g_form.getValue('u_group_name');
// Group name regular expression
var regGrpName = /^([A-Za-z0-9\-]+)$/;
// Check name against regular expression
validGroupName = regGrpName.test(group_name);
if (validGroupName == false) {
g_form.showFieldMsg('u_group_name', "Group Name must contain only letters, numbers or dashes. ", 'error');
//Do not submit
return false;
}
//Check if google group already exists
var rec = new GlideRecord('u_broad_user_accounts');
rec.addQuery('u_account_email', new_group_email);
rec.query();
while (rec.next()) {
g_form.showFieldMsg('u_group_name',rec.u_account_email + " already exists as an account.",'error');
return false;
}
//Group Members Email List separated by commas
var group_members = g_form.getValue('u_group_members');
// comma separate list
var member_split = group_members.split(',');
// loop over list of email addresses
for (var n = 0; n < member_split.length; n++) {
// trim whitespace
var member_info = trim ? member_split[n].trim() : member_split[n];
// validation regular expression
var validRegExp = /^\w+((-\w+)|(\.\w+))*\#[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// check each item against regular expression
if (member_info.search(validRegExp) == -1) {
g_form.showFieldMsg('u_group_members', "Group Members contains an invalid email address. " + member_info, 'error');
return false;
}
}
}

Javascript form validation for date not working

I have this javascript running on a html form. really struggling to get this working, Nothing pops up, no alerts at all. any help please. My code is probably terrible but I have only been using javascript for 4 weeks
function validate(form){
var vRunnerId = document.forms["submitrunnertime"]["RunnerId"].value;
var vEventId = document.forms["submitrunnertime"]["EventId"].value;
var vDate = document.forms["submitrunnertime"]["Date"].value;
var vFinishTime = document.forms["submitrunnertime"]["FinishTime"].value;
var vPosition = document.forms["submitrunnertime"]["Position"].value;
var vCategoryId = document.forms["submitrunnertime"]["CategoryId"].value;
var vAgeGrade = document.forms["submitrunnertime"]["AgeGrade"].value;
var vPB = document.forms["submitrunnertime"]["PB"].value;
var validFormat = /^\d{4}-\d{2}-\d{2}$/;
if (/\D/.test(vRunnerId)){
alert("Please only enter numeric characters only for your Runner ID");
return false;
}
if (/\D/.test(vEventId)){
alert("Please only enter numeric characters only for your Event ID");
return false;
}
if (!validFormat.test(vDate){
alert("Please enter date in YYYY-MM-DD");
return false;
}
return true;
}
I don't see your vDate being defined anywhere in that function, so it looks like you forgot to add that to your javascript.
You are grabbing the <input> value twice. Once here:
var vDate = document.forms["submitrunnertime"]["Date"].value;
and again in the check:
if (!validFormat.test(vDate.value)){
You're trying to find the .value of a .value which I would assumed would throw en error.

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

Categories

Resources