Uncaught ReferenceError: item is not defined - javascript

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.

Related

Convert Javascript array back into JQuery-type object

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.

Passing variables to a class method in Javascript

This is the first time I'm trying to work with classes (or the Javascript equivalent to classes).
With the following code I get the error: Missing ( before function parameters. in Zeile 8
Do I have some error in the syntax here? Or is it not possible to pass variables to a "class method"?
function tagConstructor() {
this.tagTypeList = [
"brand",
"category",
];
this.tags = {};
}
function tagConstructor.prototype.addTag = function(tagType, tag) { // This is line 8 where the error occurs
// Only add tag if tag type exists in tagTypeList
if (this.tagTypeList.indexOf(tagType) > -1) {
this.tags[tagType] = tag;
}
}
function main() {
var test = new tagConstructor();
test.addTag("brand", "Adidas");
test.addTag("gender", "Damen");
}
It's not
function tagConstructor.prototype.addTag = function
It's
tagConstructor.prototype.addTag = function

Get And Append ID in Javascript

Hey I tried this code for my project and it returns some bad results. getting the last Id does not work properly .
function regionDropDownChanged() {
var selectedRegionId = getRegionDropDown();
if (selectedRegionId !== null) {
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
} else return;
$.get("/Common/JsonFunction/GetEnterprisesOfRegion", { regionId: val }, function (fields) {
fillDropDown(fields, getEnterpriseDropDown());
enableEnterpriseDropDown();
});
}
Also enableEnterpriseDropDown() Dropdown does not work after selecting IDs.
function enableEnterpriseDropDown() {
var enterpriseDropDown = getEnterpriseDropDown();
$(enterpriseDropDown).prop('disabled', false);
}
other methods that I use in my project
function getRegionDropDown() {
var dropDown = $("#RegionId").val();
return dropDown;
}
function getEnterpriseDropDown() {
var dropDown = $("#EnterpriseId");
return dropDown;
}
remember that I use Choosen Plugin.
Here you are using array of selectedRegionId but it is a value, as you have called getRegionDropDown() which returns a single value.
var selectedRegionId = getRegionDropDown();
So,
you may get undefined in alert in these lines
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
If you create a Fiddle then it would be better to solve you problem.

Jquery function returning function code not value

I am iterating over a list nested within a div (.catHOLDER), finding the img tag and trying to return the img src. The problem I have is that the function is returning all of the function source code instead of the string value, but oddly if I alert in the loop it returns the string value;
$(document).ready(function(){
function getnestedimg() {
$('.catHOLDER ul').children('li').each(function(i,value) {
var imgstr = $(value).find('img').attr('src');
if (imgstr !== undefined) {
alert(imgstr);
}
});
}
getnestedimg();
});
The above code will display an alert with path of the img src, but if I try to return imgstr it returns me the function code instead;
$(document).ready(function(){
function getnestedimg() {
$('.catHOLDER ul').children('li').each(function(i,value) {
var imgstr = $(value).find('img').attr('src');
if (imgstr !== undefined) {
return imgstr;
}
});
}
getnestedimg();
});
Returns the following;
function getnestedimg() {
$('.catHOLDER ul').children('li').each(function(i,value) {
var imgstr = $(value).find('img').attr('src');
if (imgstr !== undefined) {
//alert(imgstr);
//ret urn gotya;
return imgstr.val();
}
});
}
Can anyone help me in my plight, or if there is a better way to iterate over the children tags nested with the div?
The return statement inside the getnestedimg function, is acually inside the nested anonymous function you pass to each. That's why it's not returning any value to the caller of getnestedimg. You should store this value in a function variable of getnestedimg, as suggested.
Also, I recommend you read up on closures.
I'd use something like this:
var image_src = $('.catHOLDER ul > li img[src]').first().attr('src');
> li img[src] selects only img tags that have a src attribute and are descendants of li elements. .first() grabs only the first one.
If no elements match those conditions, image_str === undefined.
$.fn.extend({
getsrc : function() {
return $(this).find(">ul> li img").map(function() {
return $(this).attr("src");
});
}
});
$(document).ready(function() {
var catHOLDERimgsrc = new Array();
catHOLDERimgsrc=$(".catHOLDER").getsrc();
console.log(catHOLDERimgsrc);
})
but a plugin for this ? i would do it direct :
$(document).ready(function() {
var catHOLDERimgsrc = new Array();
catHOLDERimgsrc=$(".catHOLDER").find(">ul> li img").map(function() {
return $(this).attr("src");
});
console.log(catHOLDERimgsrc);
})
imo the nicest way to iterate to get a set of value arranged in an array (that is if you want all the images src otherwise you change selector then if not enough you can do anything inside the map function)

Call function in parent's parent from inside jquery's .each

I've created a 'class' in javascript called QuoteProductService(), see below.
I've added two functions to the prototype and now, I'm trying to call one of the functions (getQuoteProductFromArray) from within a jquery $.each inside the other function (getFakeQuoteProducts). This doesn't work. I've tried adding 'this.', but this also does not work, because 'this' inside the .each refers to the current element in the loop.
How should I do this ?
function QuoteProductService() {
}
QuoteProductService.prototype.getQuoteProductFromArray = function(quoteproductarray, quoteproductid){
var founditem=null;
// do stuff
return founditem;
}
QuoteProductService.prototype.getFakeQuoteProducts = function(){
// do something to fill the mappedQuoteProducts array
$.each(mappedQuoteProducts, function (index, quoteproduct) {
if (quoteproduct!=-null) {
if (quoteproduct.parentid != "") {
// this is where it goes wrong :
var parent = getQuoteProductFromArray(mappedQuoteProducts, quoteproduct.parentid);
if (parent != null) {
parent.attachChild(quoteproduct);
}
}
}
});
}
Save a reference to your QuoteProductService instance before calling each
QuoteProductService.prototype.getFakeQuoteProducts = function(){
var _this = this;
// do something to fill the mappedQuoteProducts array
$.each(mappedQuoteProducts, function (index, quoteproduct) {
if (quoteproduct!=-null) {
if (quoteproduct.parentid != "") {
// this is where it goes wrong :
var parent = _this.getQuoteProductFromFlatArray(mappedQuoteProducts, quoteproduct.parentid);
if (parent != null) {
parent.attachChild(quoteproduct);
}
}
}
});
}
Add var self = this; to the beginning of the getFakeQuoteProducts function. Then call getQuoteProductFromFlatArray like this: self.getQuoteProductFromFlatArray.
First of all you provided wrong method name - getQuoteProductFromFlatArray instead of getQuoteProductFromArray. Secondly in JS you must provide scope for instance methods.
Easiest way to achieve this is to store this reference into some other, private variable. See the example below.
function QuoteProductService() {
}
QuoteProductService.prototype.getQuoteProductFromArray = function(quoteproductarray, quoteproductid){
var founditem=null;
// do stuff
return founditem;
}
QuoteProductService.prototype.getFakeQuoteProducts = function(){
var me = this; // store this into me
// do something to fill the mappedQuoteProducts array
$.each(mappedQuoteProducts, function (index, quoteproduct) {
// this === me will return false
if (quoteproduct!=-null) {
if (quoteproduct.parentid != "") {
// this is where it goes wrong :
var parent = me.getQuoteProductFromArray(mappedQuoteProducts, quoteproduct.parentid);
if (parent != null) {
parent.attachChild(quoteproduct);
}
}
}
});
}

Categories