I am working on js validation and want to pass one function into another but i got error "Uncaught ReferenceError: item is not defined".
My code:
validation();
function validation() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,10})$/;
function common_inputs() {
var inputs = $(' input').toArray();
inputs.forEach(function(item) {
var element = $(item);
if (!element.val() == "") {
element.closest('.my__item').removeClass('error');
}
if ( !reg.test(element.val())) {
element.closest('.my__item').addClass('error');
}
})
}
function inputValidatorClick() {
common_inputs()
var element = $(item);
if (element.val() == "") {
element.closest('.my__item').addClass('error');
}
}
$('.my-button').click(inputValidatorClick)
$(' input').keyup(common_inputs)
}
},
It seems that there is problem with passing argument "item", but i am new in JS and have no idea how to solve it.
Does anyone knows how to solve it?
i would like to have it in one function - common_inputs. To not copy
the same part of code
I see that inside your inputValidatorClick function, you do something that is already inside common_inputs function.
Also, you can remove validation which is just used to wrap common_inputs function.
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,10})$/;
function common_inputs() {
$('input').each(function () {
$(this).closest('.my__item').removeClass('error');
});
$('input').filter(function () {
return this.value === '' || !reg.test(this.value);
}).each(function () {
$(this).closest('.my__item').addClass('error');
});
}
$('.my-button').click(common_inputs);
$('input').keyup(common_inputs)
First, we collect all of the <input> tags and remove all of the error classes from the parents (my__item).
Then, we filter the inputs which have invalid values (empty or not match with the regex pattern). From there, We add class error to the parents.
For the code below, I wanted to make the _formsOk function work for both Javascript arrays and "JQuery objects". In function1(), I tried to create a Javascript array with all DOM elements except those that have a parent element with id="objectTypesContainer". Basically, function1() filters out the DOM elements I don't want before calling _formsOk() function, which does the actual form validation.
function1() {
var allForms = $('form:not(.vv_hidden)', this.selectMarketsContainer);
var nonObjectTypeForms = [];
allForms.each(function () {
if ($(this).parent().attr("id") !== "objectTypesContainer"){
nonObjectTypeForms.push($(this)[0]);
}
});
return this._formsOk(nonObjectTypeForms);
},
_formsOk: function($forms) {
var formOk = true;
console.log(typeof $forms)
$forms.each(function () { // This line fails
var validator = $(this).validate(DEFAULT_VALIDATION_OPTIONS);
if (!(validator && validator.form())) {
formOk = false;
}
});
return formOk;
},
However, I realized that because nonObjectTypeForms is now a JS Array rather than a "JQuery Object", the line marked (// This line fails) now fails.
The original code looked like this:
function1() {
var allForms = $('form:not(.vv_hidden)', this.selectMarketsContainer); // This is a "JQuery object", so no error occurs
return this._formsOk(allForms);
},
_formsOk: function($forms) {
var formOk = true;
console.log(typeof $forms)
$forms.each(function () { // This line fails
var validator = $(this).validate(DEFAULT_VALIDATION_OPTIONS);
if (!(validator && validator.form())) {
formOk = false;
}
});
return formOk;
},
Is there a way I can convert a JS array into a JQuery object ? I don't want to change _formsOk function definition just yet.
Instead of putting all elements in a new array, just use .filter() from the jQuery object.
allForms.filter(function () {
return $(this).parent().attr("id") !== "objectTypesContainer")
});
This will remove all the items you don't need in your selection and now allForms will only have the wanted elements.
I would like some help assigning function to object. I have JSON file containing function names (as string ofc...) and in my code I have already existing functions. I don't want this functions to be called just assigned so I can call them later.
I also want to be able to pass a custom function as a string from JSON file. I tried to parse it but I get Unexpected token m...
operations.push --> run: is where I want to assign function.
This is my code with what I have tried so far:
async function operate(schemaObject) {
let operations = [];
for (let operation in schemaObject.operate) {
if(schemaObject.operate.hasOwnProperty(operation)) {
//Function name as a string ex: "matchIntegerOrUnlimited"
let functionName = schemaObject.operate[operation].action;
//Function parameter (val) ex: "test 123"
let functionParam = schemaObject.operate[operation].parameter;
//Custom Function ex: "return alert(Hello)
if (operation.custom) {
operations.push({
run: new Function("test 123", return alert("123"),
on: schemaObject.operate[operation].key
});
} else {
//Push existing Function matchIntegerOrUnlimited()
operations.push({
run: functionName, //"matchIntegerOrUnlimited"
on: schemaObject.operate[operation].key
});
}
}
}
console.log(operations);
return operations;
}
function matchIntegerOrUnlimited(val) {
if (contains(val, unlimitedPattern)) {
return 10000;
} else {
let number = val.match(numberPattern)[0];
return parseInt(number, 10);
}
}
So I expect to be able to just assign function that can be called later by giving a existing function name as Sting... and also if possible to give a custom function as a String
In a Vue component's methods I read this code where a function is defined this way
methods : {
onEditorChange({ editor, html, text }) {
console.log('editor change!', editor, html, text)
this.content = html
}
}
I checked the code and it is working. Can we declare formal parameters to a function like that ?
You can find the code snippet in
https://github.com/surmon-china/vue-quill-editor
This is known as Destructuring.
From:
http://2ality.com/2015/01/es6-destructuring.html#parameter-handling
In ECMAScript 5, you’d implement selectEntries() as follows:
function selectEntries(options) {
options = options || {};
var start = options.start || 0;
var end = options.end || getDbLength();
var step = options.step || 1;
···
}
In ECMAScript 6, you can use destructuring, which looks like this:
function selectEntries({ start=0, end=-1, step=1 }) {
···
};
file: dojo/dir1/utils/XmlJsonUtils.js
// Author: Rajat Khandelwal
define([
"dojo/_base/declare" // declare
], function(declare){
return declare("dir1.utils.XmlJsonUtils",[],{
parseXml : function (xml) {
var self=this;
var dom = null;
if (window.DOMParser) {
try {
dom = (new DOMParser()).parseFromString(xml, "text/xml");
}
catch (e) { dom = null; }
}
else if (window.ActiveXObject) {
try {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) // parse error ..
window.alert(dom.parseError.reason + dom.parseError.srcText);
}
catch (e) { dom = null; }
}
else
alert("cannot parse xml string!");
return dom;
},
xml2json : function (xmldata)
{
var self=this;
if(xmldata.firstChild==null)
{
return {name:xmldata.nodeName+": (value null)", checked: true}
}
else if(xmldata.firstChild.nodeType==3)
{
return {name:xmldata.nodeName+": "+xmldata.firstChild.nodeValue, checked:true}
}
else
{
var mychildren=[];
var i=0;
var nochildren=xmldata.childElementCount
for(i=0;i<nochildren;i++)
{
var j=self.xml2json(xmldata.childNodes[i])
mychildren[i]=j
}
var ret= {name:xmldata.nodeName, children:mychildren, checked:true}
return ret
}
},
convert2arr : function (result,ctr,res_arr)
{
var self=this;
if(result[ctr].checked[0]==false)
return;
if(result[ctr].children==undefined)
{
var name=result[ctr]['name'][0];
var kv = name.split(': ');
if(kv[1]=="(value null)")
kv[1]="";
res_arr.push.apply(res_arr,["<",kv[0],">",kv[1],"</",kv[0],">"]);
return ctr+1;
}
else
{
var i=ctr;
var new_ctr=ctr;
var no_children=result[ctr].children.length;
res_arr.push.apply(res_arr,["<",result[ctr].name[0],">"])
for(i=0;i<no_children;i++)
{
new_ctr=self.convert2arr(result,result[ctr].children[i]._0,res_arr)
}
res_arr.push.apply(res_arr,["</",result[ctr].name[0],">"]);
return new_ctr;
}
},
convert2xml : function (result)
{
var arr=[]
self.convert2arr(result, 0, arr)
return arr.join('')
}
})
})
but when in the code I require the dir1.utils.XmlJsonUtils, it says Uncaught Error: declare XmlJsonUtils: base class is not a callable constructor. What is the correct way to declare some utility functions.
And those should be like static functions. I don't want to do x=new XmlJsonUtils(); x.parseXml(..). I want to do XmlJsonUtils.parseXml(..)
Your class should not have to have the constructor method defined, dojo.declare is supposed to handle this.. However, doing so doesnt hurt, simply define a blank constructor: function() { }. I suspect youre facing some sort of bug.
The define is as should be, 'define' is used for the require-scope, when running require(["my.module"]), its expected to have a define method, which returns the base class via declare.
file: dojo/dir1/utils/XmlJsonUtils.js:
define([
// requirements
"dojo/_base/declare",
"dir1/utils/Toolkit" // sample in-package dependency
"./Toolkit" // Same as Above
], function (declare) {
// no slash separator, use dot with declare,
// use a reference and return on last line
var Klass = declare(
/// declaredClass: string, moduleUrl with dot-separater + filename /.js//
"dir1.utils.XmlJsonUtils",
/// base class: Array(mixins)
[],
/// class scope
{
_methodMeantToBePrivate: function() { },
randomInstanceMethod: function() { }
}
); // end declare
// set any aliases, which you want to expose (statics)
Klass.StaticCallable = function() {
// careful with your scope access inhere
}
// return the declared class to 'define'
return Klass;
}); // end define
This way (you must have a reference, either pulled in with require or getObject), you could use the StaticCallable function without initializing / constructing an instance of the module. AMD compliant syntax is like so:
require(["dir1/utils/XmlJsonUtils"], function(xmlUtils) {
xmlUtils.StaticCallable();
});
or if previously required
var xmlUtils = dojo.getObject("dir1.utils.XmlJsonUtils")
xmlUtils.StaticCallable();
A specific example could be a versatile class like the following, where both instance and static access is possible. Base class defines 'tools', derived class defines the variables the 'tools' operate on - and if instantiated, the default topics can be subscribed - [ MessageBusBase | MessageBus ]
The issue: in your code.
return declare("dir1.utils.XmlJsonUtils",[],{
parseXml : function (xml) {
Instead of dir1.utils.XmlJsonUtils use dir1/utils/XmlJsonUtils, i.e., use slashes instead of dots in your function declaration.