how do I pass count integer into a function? - javascript

Here is where I set up my var adultOptions and in this var you will see name="adult'+i+'Name" /> I want that i to be the loop number you see below.
Any ideas?! Thank you
var adultOptions =
'<input type="text"'+
'placeholder="First & Last Name"'+
'required name="adult'+i+'Name"/>'
$('#adults').on('change',function(i){
numberAppend = $('#adults').val();
for(i=0; i<numberAppend; i++){
$(adultOptions).appendTo('#adultOptions');
}
});

You are nearly correct with your method. What you are lacking is, maybe the knowledge that a function can be stored in a variable in javascript.
So, now with this knowledge, you can make adultOptions point to a function, like this:
var adultOptions = function(i) {
return '<input type="text"'+
'placeholder="First & Last Name"'+
'required name="adult'+i+'Name"/>';
}
and, then use it like this:
$('#adults').on('change',function(i){
numberAppend = $('#adults').val();
for(i=0; i<numberAppend; i++){
$(adultOptions(i)).appendTo('#adultOptions');
}
});

Your string is being defined outside of your for loop (where i is being defined). Put it inside and you should be good.

Related

How to map within a for loop

We need to map an object array within a for loop, which actually works, but the editor is giving us a warning saying not to put a function within a loop:
for(var i=0; i<$scope.data.list.length; i++){
$scope.data.list[i].isRowSelected=false;
var pos1 = $scope.selectedItems.map(function(e) { return e.sys_id; }).indexOf($scope.data.list[i].sys_id);
if(pos1!==-1){
var add = $scope.selectedItems.indexOf($scope.data.list[i].sys_id);
$scope.selectedItems.splice(add,1);
}
}
To mitigate this, we're thinking about creating a separate function for the mapping and then calling it within the loop, like this:
function mappingID(e){
return e.sys_id;
}
However, when we call upon it within the loop, we're lost as to what to pass in...any suggestions? Thanks!
two things, create a function outside the loop and avoid repeating indexing and object nesting. It will make your code much cleaner and easier to reason about. I'm pretty sure this whole function could be done a lot better but I'm not sure of the bigger scope
var items = $scope.selectedItems;
var sys_id = function(e) { return e.sys_id; }
for(var i=0; i<$scope.data.list.length; i++){
var data = $scope.data.list[i]; // might be a better name for this...
data.isRowSelected=false;
var pos1 = items.map(sys_id).indexOf(data.sys_id);
if(pos1!==-1){
var add = items.indexOf(data.sys_id);
items.splice(add,1);
}
}
The comments suggest lodash, which is a good suggestion. For the purposes of your original question, however, you can declare the function mappingID as you have it, and simply put
var pos1 = $scope.selectedItems.map(mappingID).indexOf($scope.data.list[i].sys_id);
and that will do the job.
You don't need to bring lodash to handle this, you can use find: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
for(var i=0; i<$scope.data.list.length; i++){
$scope.data.list[i].isRowSelected=false;
var item = $scope.selectedItems.find(e => (e.sys_id === $scope.data.list[i].sys_id));
if (item) {
$scope.selectedItems.splice(item,1);
}
}
Also I suggest changing selectedItems to an plain-object/Map/Set so you can lookup in constant time.
To avoid doing the same mapping on each iteration of the loop, move the mapping outside the loop:
var idArr = $scope.selectedItems.map(function(e) { return e.sys_id; })
$scope.data.list.forEach(item => {
item.isRowSelected=false;
var pos1 = idArr.indexOf(item.sys_id);
if(pos1!==-1){
var add = $scope.selectedItems.indexOf(item.sys_id);
$scope.selectedItems.splice(add,1);
}
})

inovke functions javascript using while

can anyone tell me what is wrong here im just try to invoke this list of functions using array and while if it's possible thanks in advance.
var funciones = ["basicas();", "likeFbk();", "cambiarFondo();"],
i = 0;
while (funciones[i]) {
funciones[i];
i++;
}
jslint show this errors:
91 Expected an assignment or function call and instead saw an expression. funciones[i];
92 Unexpected '++'.
Solved, I use "i += 1;" instead of "i++;" and update the list of functions treated as a string, here is the code:
var funciones = [basicas, likeFbk, cambiarFondo], i = 0;
while (funciones[i]) {
funciones[i]();
i += 1;
}
thank's guys!
try it this way (not sure what you intend to do though, i am guessing you want to iterate unless there is no value at ith index)
var funciones = [basicas, likeFbk, cambiarFondo], i = 0;
while (funciones[i])
{
funciones[i]();
i++;
}
You can't invoke functions like that. The functions array is just a list of strings and not a list of functions. You have two ways of doing this:
Instead of list of strings, use list of functions as below:
var functions = [basicas, likeFbk, cambiarFondo];
while (i in funciones) {
functions[i]();
}
Use eval to evaluate string that contains javascript executable code:
var funciones = ["basicas();", "likeFbk();", "cambiarFondo();"],
i = 0;
while (funciones[i]) {
eval(funciones[i]);
i++;
}
Always go for the first approach, because the second approach is considered as evil.
Or if you prefer
var call = Function.call;
[basicas, likeFbk, cambiarFondo].forEach(call, call);
How this works is left as an exercise.

Trying to avoid eval getting array element from window object

I've got a function that wants to access a global variable, the name of which arrives as a string argument. This is how it looks now, using eval:
function echoVar(whichone){
document.write(eval(whichone));
}
I thought I'd just use the window[] syntax and have this:
function echoVar(whichone) {
document.write(window[whichone]);
}
If I create a var and call it like this, it doc writes ABC as expected:
var abc = "ABC";
echoVar("abc");
If the var I want to access is an array element though, it doesn't work:
var def = ["DEF"];
echoVar("def[0]"); //fails with undefined
Obviously that's actually executing window[def[0]] which rightly gives undefined (because there's no variable called DEF). What I actually want to happen is that it executes window["def"][0].
The only way I know to achieve this, is to do a split on the whichone parameter with "[" as the delimiter and then use the split [0] as the window index and a parseInt on split [1] to get the index, like this:
function echoVar(whichone){
if(whichone.indexOf("[")==-1){
document.write(window[whichone]);
}
else{
var s = whichone.split("[");
var nam = s[0];
var idx = parseInt(s[1]);
document.write( window[nam][idx] );
}
}
Am I overlooking something obvious? I'd rather keep the eval than have to do all that.
If you dislike using eval in your code, you can always do this:
function echoVar(whichone) {
document.write(Function("return " + whichone)());
}
Unless this is some sick experiment, you should never be writing Javascript code that looks like this. This is terrible; you need to re-think your design. I know this isn't what you're looking for, but it's the right answer.
The fact is you've got a piece of a javscript expression in a string so you either have to parse it yourself or use eval to parse it for you unless you change the way it's passed like this:
function echoVar(a,b) {
var x = window[a];
if (b) {
x = x[b];
}
document.write(x);
}
And, then you can pass it differently like this:
var def = ["DEF"];
echoVar("def", 0); // def[0]
You could even make this support multiple dimensions if you needed to.
function echoVar(a) {
var x = window[a];
for (var i = 1; i < arguments.length; i++) {
x = x[arguments[i]];
}
document.write(x);
}
var def = {myObject: {length: 3}}
echoVar("def", "myObject", "length"); // def["myObject"]["length"] or def.myObject.length
You can see it work here: http://jsfiddle.net/jfriend00/dANwq/
It would be simpler to lose the brackets and call the item with dot notation
function reval(s, O){
s= String(s);
O= O || window;
var N= s.split(".");
while(O && N.length) O= O[N.shift()];
return O || s;
}
window.def= ['definition'];
alert(reval('def.0'))
/* returned value: (String)
definition
*/

Dynamically create variable in JavaScript function

I cannot get this to work:
function formvalidation()
{
var SiteNum= document.getElementsByName("sitesinput")[0].value;
var i=1;
while (i<=SiteNum)
{
var SitePhone= document.getElementsByName(site['i'])[0].value;
alert(SitePhone);
i++;
}
}
If I alert like so: alert('document.getElementsByName(site["'+i+'"])[0].value'); it will display the following:
document.getElementsByName(site["1"])[0].value
document.getElementsByName(site["2"])[0].value
document.getElementsByName(site["3"])[0].value
But I cannot get it to go into a variable.
Thanks for looking,
B.
Try replacing the line
var SitePhone= document.getElementsByName(site['i'])[0].value;
for
var SitePhone= document.getElementsByName(site[i])[0].value;
Remove the quotes from i. Use a for loop since it fits the use case better than a while loop.
function formvalidation()
{
var SiteNum= document.getElementsByName("sitesinput")[0].value,
SitePhone;
for(var i=1; i<=SiteNum; i++)
{
SitePhone = document.getElementsByName(site[i])[0].value;
alert(SitePhone);
}
}
Also, JavaScript does not have block-level scoping, only function-level.
I like this solution, however it wont work without the quotes (") i.e. if do everything the same, but put the name in myself, like ("site[1]") - it will work.
I see where you're headed now.
SitePhone = document.getElementsByName('site[' + i + ']')[0].value;
You are putting quotes around the i in the line
var SiteNum = document.getElementsByName(site['i'])[0].value
which is looking for the element keyed by the string 'i' instead of the value of the variable i. Try removing the quotes.
Try
alert(document.getElementsByName(site[i])[0].value);

for loop inside jquery function

I am trying to repeat something inside a jquery function. I tried a for loop, but it seems it doesnt like the syntax.
for instance i have the variable
var number = 2;
now i have
$('tr').html('<td id="'+number+'"></td>');
what i want to do is loop from 0 to number (0,1,2) so that in the end i end up having 3 .
Thanks
There is probably a better way, but this should work.
var loops = [1,2,3];
$.each(loops, function(index, val) {
$('tr').html('<td id="myCell' + index + '"></td>');
});
This should also work (regular JS):
var i;
for(i=0; i<3; i++) {
$('tr').html('<td id="myCell' + i + '"></td>');
}
Note how i prefixed id with the word 'myCell', to ensure XHTML compliancy. (thanks to #Peter Ajtai for pointing that out).
EDIT
I just noticed another problem - you're using the .html function to add the cells. But .html replaces the entire html of the matched element. So you'll only ever end up with the last cell. :)
You're probably looking for the .append function:
$('tr').append('<td id="myCell' + i + '"></td>');
EDIT 2 -- moved the double quote before myCell rather than after.
Heres an option using an anonymous function.
$('TR').html(
function(){
var content='';
for (var i=0; i<=2; i++ ){
content=content+'<td id="id_'+i+'"></td>';
}
return content;
}
)
This works for me:
loop.forEach((amount) => {
// your code
}

Categories

Resources