Adding the results of a function to an array - javascript

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]'));

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.

Function Javascript return

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);
}

Javascript return variables from each function

Looping through children elements using each.
var divHeights = [];
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
alert(divHeights); // fails
How can I return the divHeights variable?
I've tried
var hts = ('#parent').children('div').each(function () { ...
but obviously that won't work.
You can do this in better way using .map() like:-
var divHeights = $('#parent').children('div').map(function () {
return this.clientHeight || 0;
}).get();
DEMO FIDDLE
The divHeights variable is available all the time. You can just assign it to a variable whenever you want:
var hts = divHeights;
This will just be another reference to the array, so you can do that any time after the array is created, even before you have put any values into it:
var divHeights = [];
var hts = divHeights;
$('#parent').children('div').each(function () {
divHeights.push(this.clientHeight);
});
You can of couse just use the variable divHeights instead of the variable hts when you want to use the result, or just use the variable hts instead of divHeights from start.
You could make it into a function like this:
function getHeights() {
return $('#parent div').map(function() {
return this.clientHeight;
});
}
Then you can just call the function wherever you like to get the array contents.

JS function to coffeescript, with jQuery .map and Selectors as param

I'm refactoring some JS code to CoffeeScript, and having a problem with a function.
This is the JS that works:
$(".comformt_QA").change(function(){
var array = $(".comformt_QA").map(function() {
return $(this).val();
}).toArray();
$("[name='comfort_qualitative_assessment.global_comfort_index']").val(
calc_qualitative_assessment_array(array)
).change();
});
My goal is to use this snipplet as a function, and be able to call:
class_to_calc_qualitative_assessment_array(".comformt_QA", "[name='comfort_qualitative_assessment.global_comfort_index']");
Here's the CoffeeScript:
#class_to_calc_qualitative_assessment_array = (class_param, target) ->
array = []
$(class_param).change ->
array = $(class_param).map( ->
$(this).val()
)
$(target).val(calc_qualitative_assessment_array(array)).change()
array is always empty...
Thoughts?
If you compile your coffee code to Javascript this would be the result:
this.class_to_calc_qualitative_assessment_array = function(class_param, target) {
var array;
array = [];
$(class_param).change(function() {
return array = $(class_param).map(function() {
return $(this).val();
});
});
return $(target).val(calc_qualitative_assessment_array(array)).change();
};
Coffeescript transpiles the # to the this keyword in JS. Also you don't have returns within your function - this leads to coffeescript returning the last assigned value of the function.
Maybe this would be a working approach:
class_to_calc_qualitative_assessment_array = (class_param, target) ->
array = []
$(class_param).change ->
array = $(class_param).map( ->
$(#).val()
)
return
$(target).val(calc_qualitative_assessment_array(array)).change()
return
Transpiled this looks like this:
var class_to_calc_qualitative_assessment_array;
class_to_calc_qualitative_assessment_array = function(class_param, target) {
var array;
array = [];
$(class_param).change(function() {
array = $(class_param).map(function() {
return $(this).val();
});
});
$(target).val(calc_qualitative_assessment_array(array)).change();
};

_.each find value in array return true or false. using underscore js

//find value in array using function checkValue using underscoreJS _.each.
//return true, else false.
var helloArr = ['bonjour', 'hello', 'hola'];
var checkValue = function(arg) {
_.each(helloArr, function(helloArr, index) {
if (arg[index] === index) {
return true;
}
return false;
});
};
alert(checkValue("hola"));
The problem with your code is that, _.each will iterate through all the elements of the array and call the function you pass to it. You will not be able to come to a conclusion with that, since you are not getting any value returned from it (unless you maintain state outside _.each).
Note that the values returned from the function you pass to _.each will not be used anywhere and they will not affect the course of the program in any way.
But, instead, you can use _.some as an alternate, like this
var checkValue = function(arg) {
return _.some(helloArr, function(currentString) {
return arg === currentString;
});
};
But, a better solution would be, _.contains function for this purpose. You can use it like this
var checkValue = function(arg) {
return _.contains(helloArr, arg);
};
But, since you have only Strings in the Array, the best solution would be to use Array.prototype.indexOf, like this
var checkValue = function(arg) {
return helloArr.indexOf(arg) !== -1;
};
Try this:
var helloArr = ['bonjour', 'hello', 'hola'];
var checkValue = function(arr, val) {
_(arr).each(function(value) {
if (value == val)
{return console.log(true);}
else {return console.log(false);}
});
};
console.log(checkValue(helloArr,'hello'));
/* Output
false
true
false*/

Categories