JavaScript & jQuery Function Error - javascript

I am making a generic text validation function with jQuery. I made the function text and I pass the id,requirement,expression,offset,limit into the function. The way I have made it is to help me run the function easily on single input change and on the submit of the whole form. I have made the function but I can't get it to run.
var Val = {
'text' : function(event, ident,req,regexp,offset,limit) {
var ele = $(document.getElementById(ident));
if(req == 1 && ele.val().length < 1) {
Val.errors = true;
$("#"+ident+"Error").html("Please enter your " + ele.attr("title"));
$("#"+ident+"Error").show("fast");
} else if(ele.val().length <= offset || ele.val().length > limit) {
Val.errors = true;
$("#"+ident+"Error").html(ele.attr("title") + " should be between " +offset+ " & " +limit+ " charecters long");
$("#"+ident+"Error").show("fast");
} else if(regexp != null) {
switch (regexp) {
case 'text':
var regEx = /^([a-zA-Z]+)$/; break;
case 'number':
var regEx = /^([0-9]+)$/; break;
case 'email':
var regEx = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; break;
case 'date':
var regEx = /^([123]0|[012][1-9]|31)-(0[1-9]|1[012])-(19[0-9]{2}|2[0-9]{3})$/; break;
case 'alphanum':
var regEx = /^([a-zA-Z0-9._-]+)$/; break;
default:
var regEx = /^([a-zA-Z0-9._-]+)$/; break;
}
if(!regEx.test(ele.val())) {
Val.errors = true;
$("#"+ident+"Error").html(ele.attr("title") + " is not valid");
$("#"+ident+"Error").show("fast");
}
}
},
'send' : function (){
if(!Val.errors) {
$('#form').submit();
}
}
}
The calling code of the function:
$(document).ready(function(){
$('#send').click(function(){
Val.text('test', 1, 'email', 10, 50);
Val.send();
});
$('#test').bind('change', Val.text);
$('#test').trigger('change', ['test', 1, 'email', 10, 50]);
});
I know I haven't yet used the expressions but I will once I see it working.
Appreciate all the help...
Thanks!

I made it work. Once the script worked properly no trigger was required. I was able to just call simply inside the change event.
$('#emailID').change(function(){
Val.text('emailID', 1, 'email', 10, 100);
});
Thanks everyone for the help anyway.

Related

In Google Docs under script control, can a paragraph inserted automatically after the insertion of a table be addressed programmatically?

I have a Google Docs document with a PARAGRAPH followed by a TABLE followed by a TABLE. Visually there is a PARAGRAPH between the two TABLEs. Programatically, however, using the following code, the run log demonstrates that there is no PARAGRAPH, viz
[1] PARAGRAPH {'LEFT_TO_RIGHT' : true, 'LINE_SPACING' : 1.15, 'SPACING_AFTER' : 0, 'SPACING_BEFORE' : 0, 'INDENT_FIRST_LINE' : 0, 'INDENT_END' : 0, 'INDENT_START' : 0}
[1/1] TEXT {} perth influencer
[2] TABLE {'BORDER_WIDTH' : 1, 'BORDER_COLOR' : '#000000'}
[3] TABLE {'BORDER_WIDTH' : 1, 'BORDER_COLOR' : '#000000'} Keyword Research Volume
...
According to the Google Apps Script documentation for appendTable:
This method will also append an empty paragraph after the table, since Google Docs documents cannot end with a table.
This paragraph can be seen with the eyes but the script as it stands cannot "see" it. That is, stepping through the child elements of the document's body fails to detect the presence of the automatically-inserted paragraph. This is a problem because I want to reduce the point size of that paragraph.
This may be a known limitation of Google Docs via Google Apps Script. Or it may be my bad code, so below are the functions that I base my assertion on. They do nothing other than report on what they find but even so, maybe I'm missing something.
The output above was generated by coding LogChildren with a parameter of type GoogleAppsScript.Document.Body and referring to the body of the generated document.
String.prototype.quoted = function () {
return "'" + this.replace(/'/g,"\\'") + "'";
}
Number.prototype.quoted = function () {
return String(this);
}
Boolean.prototype.quoted = function () {
return this ? "true" : "false";
}
function getInnerText(child) {
switch (child.getType().toString()) {
case "BODY_SECTION":
return child.asBody().getText();
break;
case "EQUATION":
return child.asEquation().getText();
break;
case "EQUATION_FUNCTION":
return child.asEquationFunction().getText();
break;
case "FOOTER_SECTION":
return child.asFooterSection().getText();
break;
case "FOOTNOTE_SECTION":
return child.asFootnoteSection().getText();
break;
case "HEADER_SECTION":
return child.asHeaderSection().getText();
break;
case "LIST_ITEM":
return child.asListItem().getText();
break;
case "PARAGRAPH":
return "";
break;
case "TABLE":
return child.asTable().getText();
break;
case "TABLE_CELL":
return child.asTableCell().getText();
break;
case "TABLE_OF_CONTENTS":
return child.asTableOfContents().getText();
break;
case "TABLE_ROW":
return child.asTableRow().getText();
break;
case "TEXT":
return child.asText().getText();
break;
case "PAGE_BREAK":
return "";
break;
case "INLINE_IMAGE":
return child.asInlineImage().getLinkUrl();
break;
default:
return child.asText().getText();
break;
}
}
function getStyles(child) {
const attribs = child.getAttributes();
const attribList = [];
for (let att in attribs) {
try {
if (null !== attribs[att])
attribList.push(att.quoted() + " : " + attribs[att].quoted());
}
catch (E) { }
}
return "{" + attribList.join(", ") + "}";
}
function LogChild(index, child) {
Logger.log("[%s] %s %s %s", index, child.getType().toString(), getStyles(child), getInnerText(child));
}
function LogChildren(body) {
function LogDeeper(cc, child) {
const childCount = child.getNumChildren();
for (let c = 0; c < childCount; c++) {
LogChild(String(cc) + "/" + String(c + 1), child.getChild(c));
}
}
const childCount = body.getNumChildren();
for (let c = 0; c < childCount; c++) {
const child = body.getChild(c);
LogChild(String(c + 1), child);
if (isParagraph(child)) {
LogDeeper(c + 1, child.asParagraph());
}
else if (isListItem(child)) {
LogDeeper(c + 1, child.asListItem());
}
}
}
function isPageBreak(elem) {
return elem.getType() === DocumentApp.ElementType.PAGE_BREAK;
}
function isText(elem) {
return elem.getType() === DocumentApp.ElementType.TEXT;
}
function isParagraph(elem) {
return elem.getType() === DocumentApp.ElementType.PARAGRAPH;
}
function isListItem(elem) {
return elem.getType() === DocumentApp.ElementType.LIST_ITEM;
}
function isTable(elem) {
return elem.getType() === DocumentApp.ElementType.TABLE;
}
Use google-docs-api 's Document#get to retrieve the document structure and if there is a intervening paragraph recorded between the two tables, issue UpdateParagraphStyleRequest to modify that paragraph.
You can access the api from apps script through Advanced Google services

Cannot read property length of undefined - Javascript

I'm new in javascript the main goal of this code is to type a question in the textbox the browser will check the question if it was in the switches statements and get the answer than write it on the paragraph's id="lable".
The function randomArray(z)-line[8]- return a random array value .
What's hapenning : Typed :"undefined" on the paragraph which has "lable" as an id .
.........................
The HTML code :
<body>
<img src="Alexs_face.png">
<p style="border:2px black solid; margin:100px 400px 50px 400px">Ask me !</p>
<p id="lable"></p>
<input id="input" type="text" autocomplete="off">
<input id="send" type="button" onclick="dosome()" value="Send">
<input id="delete" type="button" onclick="deleteVal()" value="Delete"></body>
The Javascript:
var greating , userName;
var firstHello = [[greating+userName+", How can I help you ?" ], ["Hi "+userName+" how can i help ?"] ,[ greating+", how can i help ?"]];
dosome () ;
function randomArray (z) {
var index = Math.floor(Math.random() * z.length);
return z[index];
};
function getVal() {
write(randomArray (firstHello)); /* <------ trying to write a radom value from the firstHello array
*/
var ask = document.getElementById("input").value;
return ask ;}
var ask = getVal();
function write (x){
var lable = document.getElementById("lable").innerHTML = x;
return lable ;
};
//Capitalize the first letters func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............
//............................... you can ignore this function
function dosome () {
var ask = getVal();
var question = ask.split(" ");
var date = new Date().toTimeString().split(" ")[0]; ;
var userName ="Med" ;
//5// give you different "greatings" according to ur time
if (date >= "06:00:00" && date <="11:00:00"){
greating = "Good morning ";
var alertTime=""
}
else if (date >= "11:00:00" && date <= "15:00:00"){
greating = "Good afternoon ";
var alertTime=""
}
else if (date >= "15:00:00" && date <="22:00:00"){
greating = "Good evening ";
var alertTime=""
}
else {
greating = " You should have some sleep !";
var alertTime = greating ;
};
//5//end
//
if (question[0] === "what"){
switch ( question[1]){
case "time":
switch (question[2]){
case "is":
switch (question[3]){
case "it":
write("The time is :"+date+alertTime);
break;
default:
};
break;
default:
} ;
break;
case "is":
switch (question[2]){
case "your" :
switch (question[3]){
case "name":
write("Alex !");
break;
case "father":
write("Medardo Erabti , he made me !");
break;
default:
};
break;
case "my":
switch (question[3]){
case "name":
write("Alex !");
break;
default:
};
break;
default:
};
break;
default: write("unknown");
};}
else if (question[0] === "my"){
switch (question[1]){
case "name":
switch(question[2]){
case "is":
userName = capitalize(question[3]);;
alert("Your name is saved, "+userName);
break;
default:
};
break;
default:
};
}
else if (question[0] === "should" || "could" || "may" || "can" ) {
switch (question[1]) {
case "i" :
switch(question[2]){
case "sleep":
write("Sure ! you can sleep if you want to !!");
break;
default:
}
break;
default:
};
}
if (question[0] === "who"){
switch (question[1]){
case "are":
write ("I'm Alex !");
break;
case "am":
write ("My leader !");
default:
}
};
return userName,greating ;
};
function deleteVal () {
var x = document.getElementById("lable").innerHTML = "" ;
return x ;
};
What I have tried:
Tried to disable the 'z' parametr in the function 'randomArray(z)' and replace it with the name of the array "firstHello" , Its type "undefined in the paragraf that has "lable" as an id .
In the dosome function you create a local variable named userName, the same as the global variable. The local variable will shadow the global variable for the code inside the function, so the global variable will still be undefined after calling the function.
Notes about the code in the randomArray function:
You are using Math.floor instead of Math.random.
Don't use Math.round when creating an integer random number, that will make the first and last number occur half as often as the other numbers. Use Math.floor instead.
Your loop goes two items beyond the last item in the array.
You don't need to loop at all to get an item with a specific index.
Here is code that just shows the modified randomArray function and code to call it:
var greating = 'Hello', userName = 'sir';
var firstHello = [
[ greating + " " + userName + ", How can I help you ?" ],
[ "Hi " + userName + " how can i help ?" ],
[ greating + ", how can i help ?" ]
];
function randomArray(z) {
var index = Math.floor(Math.random() * z.length);
return z[index];
}
console.log(randomArray(firstHello));

Switch statement is returning no value

I have a test i'm writing which reads in a string and then takes that string and applies it to a switch statement. I then match the string to the case and set an integer value which I pass back to the spec page which then passes the int value to another test that I use for an if statement. I cannot get the int to pass so the if statement will not work properly.
The object for switch:
var appsNotPurchased = 0;
this.checksHomeSublevel = function(mmCode) {
browser.get('https://iplan-qa.meetingmatrix.com/Home/Index/' + mmCode);
marketingObjects.level.getText().then(function(text) {
var homeText = text;
browser.get('https://iplan-qa.meetingmatrix.com/Home/Apps/' + mmCode);
expect($('div.apps-subscription > span').getText()).toEqual('iPlan Level: ' + homeText);
switch (homeText) {
case 'Select':
console.log(homeText);
appsNotPurchased = 6;
return appsNotPurchased;
break;
case 'Content':
console.log(homeText);
appsNotPurchased = 0 || 1 || 2 || 3 || 4 || 5 || 6;
return appsNotPurchased;
break;
}
});
the testSpec describe function:
describe('should upload media: ', function() {
it('should select add media', function() {
var mmCode = "ACC0572";
var appsNotPurchased = appsObjects.checksHomeSublevel(mmCode);
appsObjects.checksSubLevelSelect(mmCode, appsNotPurchased);
});
});
The object I am passing the value to:
this.checksSubLevelSelect = function(mmCode, appsNotPurchased) {
//counts the apps
apps.count().then(function(count) {
expect(count).toEqual(7);
for (var i = 0; i < count; i++) {
if (appsPlace == appsNotPurchased) {
//does something here
} else {
//does something here
}
appsPlace++;
}
});
};
You should be returning an object instead of || statement. Also return statement should be written outside switch rather than inside it.
Simplest solution would be to use a global variable appsNotPurchased which stores the value and then you can use it in your test specs without returning. But that would be a poor coding standard.
Second solution would be to return a promise of the function as protractor executes asynchronously.
Here's an example of second solution -
this.checksHomeSublevel = function(mmCode) {
var getval = marketingObjects.level.getText().then(function(text) {
switch (homeText) {
case 'Select':
console.log(homeText);
appsNotPurchased = [6];
break;
case 'Content':
console.log(homeText);
appsNotPurchased = [0, 1, 2, 3, 4, 5, 6]; //either use array or object
break;
default:
console.log("Default");
}
return appsNotPurchased;
});
return protractor.promise.fulfilled(getval);
};
and then use it like a promise in your spec -
appsObjects.checksHomeSublevel(mmCode).then(function(appsNotPurchased){
appsObjects.checksSubLevelSelect(mmCode, appsNotPurchased);
});
Use above result in your function now -
this.checksSubLevelSelect = function(mmCode, appsNotPurchased) {
//counts the apps
apps.count().then(function(count) {
expect(count).toEqual(7);
for (var i = 0; i < count; i++) {
if (appsPlace == appsNotPurchased[i]) {
//does something here
} else {
//does something here
}
appsPlace++;
}
});
};
Hope it helps.

Populate checkbox from JSON data

I am having trouble trying to re-populate a form with has come from a JSON object. I have used JSON.stringify(name) and for the value as well and it returns me the type of data format I think might work. But can't seem to get in the $.each method
function fetchOrderFromLocalStorage() {
PROCESS_SAVE = true;
var mcs = localStorage.getItem(REPORTS_KEY);
console.log(mcs);
var jsn = JSON.parse(mcs);
console.log(jsn);
if (mcs.length == 0) {
return false;
}
$.each(jsn, function (name, val) {
var $el = $("input[name='" + name + "']"),
type = $el.attr('type');
console.log(JSON.stringify(name) + ":" + JSON.stringify(val));
switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="' + val + '"]').attr('checked', 'checked');
break;
default:
$el.val(val);
}
});
//console.log(jsn);
//for (var i = 0; i < jsn.length; i++) {
// var formInput = jsn[i];
// $("form input[name='" + formInput.name + "']").val(formInput.value);
//}
}
The commented out code at the bottom works, but I want to populate checkboxs as well so I have tried some code from here that has been checked to work. So I am trying it but my data is not in the correct format. I think I want JSON.Stringify() as the sonsole give me the correct result according to jQuery docs.
try this
function fetchOrderFromLocalStorage() {
PROCESS_SAVE = true;
var mcs = localStorage.getItem(REPORTS_KEY);
console.log(mcs);
var jsn = JSON.parse(mcs);
console.log(jsn);
if (mcs.length == 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i],
$el = $("input[name='" + formInput.name + "']"),
type = $el.attr('type');
switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="'+formInput.value+'"]').attr('checked', 'checked');
break;
default:
$el.val(formInput.value);
}
}
}

Limit select2 to only accept email addresses

I have a select2 box, an I was to limit this to accept only email addresses.
I am trying to do this by writing a custom formatSelection function, as
formatSelection: function(object, container){
if(validateEmail(object.text)){
return object.text;
}
else{
return "";
}
}
I am expecting that returning an empty string would be enough to not show this input in select2, but I am getting an empty result.
As of select2 4.0 +, just use the createTag function:
createTag: function(term, data) {
var value = term.term;
if(validateEmail(value)) {
return {
id: value,
text: value
};
}
return null;
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
I have solved this. Just copy paste the code below and it will work smooth.
validate: function(value) {
if(value && value.length != 0){
var emailText = "";
var isValidEmail = true;
var isEmailLengthValid = true;
for (var i in value) {
var email = value[i];
isValidEmail = validateEmail(email);
if(isValidEmail == false){
break;
}else{
emailText = (i == 0) ? emailText : ", " + emailText;
if(emailText.length > 250){
isEmailLengthNotValid = false;
break;
}
}
}
if(isValidEmail == false){
return 'Enter a valid email address';
}else if(isEmailLengthValid == false){
return 'Maximum 250 characters allowed';
}
}
}
Also add below function validateEmail() which uses regex to validate email string.
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
it isn't clear from your question where your data source is. if the data source is from an ajax call then you can do server side validation and only return the email addresses.
but i suspect that you want to accept user input and only of valid email addresses. The Select2 docs explain the createSearchChoice function in the initialization $opts. you could insert your validateEmail function here and decide if you want to accept the new answer or not.
you might even want to write to an external DOM element any errors you find so the user knows they have to go back and correct the invalid email address.
//Allow manually entered text in drop down.
createSearchChoice: function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {id:term, text:term};
}
},
i use select2 4.01
regex validator email
function isEmail(myVar){
var regEmail = new RegExp('^[0-9a-z._-]+#{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
return regEmail.test(myVar);
}
i return only a text without id in the return json if it's no valid. in this cas, you can add alert no selectable.
createTag: function (params)
{
if(!isEmail(params.term)){
return {
text: params.term,
};
}
return {
id: params.term,
text: params.term,
};
}
In your templateResult
function formatRepoReceiver (repo) {
if (repo.loading) return repo.text;
var markup = "";
if(typeof(repo.email) == 'undefined'){
// >>>your Alert<<<<
if(!isEmail(repo.text)){
if(repo.text == ''){
return null;
}
return 'Address email no valid';
}
//----------------------------
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.text +"</span> "+
"(<span>" + repo.text + "</span>)"+
"</div>"+
"</div";
}
else{
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.name +"</span> "+
"(<span>" + repo.email + "</span>)"+
"</div>"+
"</div";
}
return markup;
}
$('.select2-tokenizer').on('change', function() {
var num= this.value
if(!$.isNumeric(num)){
$('option:selected',this).remove();
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Please enter an integer!'
})
}
});

Categories

Resources