Function Javascript return - javascript

Can you check if I return a function correct:
JS
$(eachsection).each(function() {
listfunction();
}
function listfunction(){
$(this).show();
$(this).find('a.q_weblinksprite_med').attr("onclick", construct_url);
$(this).find('.q_weblinksprite_med').text(itemTitle);
$(this).find(".status").text(itemStatus);
$(this).find('.q_rt_rowcell-1-title').text(itemCategory);
$(this).find('.q_clipline').html(itemContent);
}
What I want is just to return all content from listfunction(). Thanks!

The code you posted isn`t returning anything.
By the look, you could return a array
function listfunction(){
var myReturn = {};
$(this).show();
myReturn['url'] = $(this).find('a.q_weblinksprite_med').attr("onclick", construct_url);
myReturn['title'] = $(this).find('.q_weblinksprite_med').text(itemTitle);
myReturn['status'] = $(this).find(".status").text(itemStatus);
myReturn['category'] = $(this).find('.q_rt_rowcell-1-title').text(itemCategory);
myReturn['content'] = $(this).find('.q_clipline').html(itemContent);
return myReturn;
}
Is this what you are looking for?

Calling listfunction() from where you have it will cause you to lose scope. So if you are attempting to call $(this).show() and have it show the element you looped through, you would need to call it like this:
$(eachsection).each(function() {
listfunction(this);
}
function listfunction(element){
$(element).show();
$(element).find('a.q_weblinksprite_med').attr("onclick", construct_url);
$(element).find('.q_weblinksprite_med').text(itemTitle);
$(element).find(".status").text(itemStatus);
$(element).find('.q_rt_rowcell-1-title').text(itemCategory);
$(element).find('.q_clipline').html(itemContent);
}

Related

jquery return true or false according custom function

I want to bind following code in custom function and return true if field has value and false if field is empty. Validating with only one variable, it was easy. But when validating two array I think it can be possible only custom function. I think code becomes unnecessarily lengthy as well because of lack of custom function. Please guide me.
$(document).on('click', '.subadd', function(){
//I want to bind this code in function
var sid = [];
$('input[name="sid[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
sid.push(this.value);
}
});
var title = [];
$('input[name="title[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
title.push(this.value);
}
});
//function
//if function return true
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};
});
First you can shorten your each loop.
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
title.push(this.value);
}
You can also make a function for that, with the selector and the array as parameters.
$.validate = function(selector, array) {
$(selector).each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
array.push(this.value);
}
}
}
In the end, the main section of the code would look like this:
var sid = [];
var title = [];
$.validate('input[name="sid[]"]', sid);
$.validate('input[name="title[]"]', title);
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};

call user function in foreach loop

i have understand that i need to change the global scope of this, because in the loop this refers to the window object. But if i try to define a variable in my foreach loop via a function its not working and i dont know why although my functio returns the correct value :(
// simple class for xml import
function io() {
this.vertexes = [];
this.getVertexByID = function(id) {
this.vertexes.forEach(function(entry) {
if (id == entry.id) {
// correct element found, displayed and returned
console.log(entry);
return entry;
}
});
}
this.importXML = function(xmlString) {
cells = this.xmlToJson(xmlString);
var parent = graph.getDefaultParent();
var _this = this;
graph.getModel().beginUpdate();
try {
// addEdges
cells.XMLInstance.Edges.Relation.forEach(function(entry) {
// both will be empty but i dont understand why :(
fromVertex = _this.getVertexByID(entry.fromNode);
toVertex = _this.getVertexByID(entry.toNode);
var e1 = graph.insertEdge(parent, null, '', fromVertex, toVertex);
});
} finally {
graph.getModel().endUpdate();
}
}
Returning a value in a forEach callback has no effect. It certainly is not the return value of the function that the forEach is part of.
So change this:
this.vertexes.forEach(function (entry) {
if(id==entry.id){
//correct element found,displayed and returned
console.log(entry);
return entry;
}
});
to this:
return this.vertexes.find(function (entry) {
return id==entry.id;
});

Adding the results of a function to an array

I have numerous input boxes that I'm trying to store the names of into an array. I'm using this currently to get the names:
var getImplementedNames = function (selector){
$(selector).each(function() {
console.log($( this ).attr('name').replace('imp-', ''));
});
}
console.log(getImplementedNames('[id^=imp]'));
This works, but now I'd like to add all the reslts to an array. I've tried;
var array = [getImplementedNames('[id^=imp]')];
console.log(array);
Which returns an undefined array.
I'm not sure of how this is supposed to be properly handled.
Use .map()
var getImplementedNames = function (selector) {
return $(selector).map(function () {
return $(this).attr('name').replace('imp-', '');
}).get();
}
usage
console.log(getImplementedNames('[id^=imp]'));
Read Return Value from function in JavaScript
Your function isn't currently returning anything. Try:
var getImplementedNames = function (selector){
return $(selector).map(function() {
return $( this ).attr('name').replace('imp-', '');
});
}
console.log(getImplementedNames('[id^=imp]'));

How to call a function on string jQuery

I was reading through fluent api I got a doubt.
I want to take in a string upon which a jQuery function or example is called upon
Function
function compareThis(newString) {
function compare(newString) {
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
}
}
Where it is called as
("alerting").compareThis("alerted").compare(); //alert 'different string'
I want to pass the data/string not as parameter but as called upon.
JSFiddle
Note: I would like to call the function in similar cases like finding date interval etc
You can use prototype to add function to String class:
String.prototype.compare = function(newString){
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
};
I think you should adapt the code for your function, but it's the idea.
Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.
var compare = (function(){
var thisString;
var stringToCompare;
var create = function(sVal) {
thisString = sVal;
return this;
};
// Public
var compareThis = function(sVal) {
stringToCompare = sVal;
return this;
};
var compare = function(anotherString) {
return thisString == stringToCompare;
};
return {
create: create,
compareThis: compareThis,
compare: compare
};
}());
var b = compare.create('test').compareThis('test').compare();
alert(b);
Example fiddle

Passing variables between functions in Javascript

I have this code:
collection = (function() {
function collection(removeLinkTitle){
this.removeLinkTitle = removeLinkTitle || 'delete';
}
collection.prototype = {
removeLinkTitle: this.removeLinkTitle,
init:function(){
...some code...
this.deleteCollectionForm();
},
deleteCollectionForm:function(){
var removeFormA = $(''+this.removeLinkTitle+'');
linkLi.append( removeFormA );
removeFormA.on('click', function(e) {
e.preventDefault();
linkLi.remove();
var index = collectionHolder.data( 'index' );
collectionHolder.data( 'index', index - 1 );
});
}
};
return collection;
})();
The thing is that the var removeForm returns its value only the frst time it loads, the following times it returns undefined.
I don't want to pass the variable as an argument so, is it there any other way to do this?
Thanks !!
i think this is not really the problem, the one thing that is undefined is the, removeLinkTitle, try this:
return new collection;
so you hit your constructor, or set some other value with:
return new collection("delete item");

Categories