Dynamically create variable in JavaScript function - javascript

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

Related

Javascript on click event not reading else statement or variables

I'm trying to make a click handler that calls a function; and that function gets a string and basically slices the last character and adds it to the front, and each time you click again it should add the last letter to the front.
It seem so easy at first that I thought I could just do it using array methods.
function scrollString() {
var defaultString = "Learning to Code Javascript Rocks!";
var clickCount = 0;
if (clickCount === 0) {
var stringArray = defaultString.split("");
var lastChar = stringArray.pop();
stringArray.unshift(lastChar);
var newString = stringArray.join('');
clickCount++;
} else {
var newArray = newString.split("");
var newLastChar = newArray.pop();
newArray.unshift(newLastChar);
var newerString = newArray.join("");
clickCount++;
}
document.getElementById('Result').innerHTML = (clickCount === 1) ? newString : newerString;
}
$('#button').on('click', scrollString);
Right now it only works the first time I click, and developer tools says newArray is undefined; also the clickCount stops incrementing. I do not know if it's an issue of scope, or should I take a whole different approach to the problem?
Every time you click you are actually reseting the string. Check the scope!
var str = "Learning to Code Javascript Rocks!";
var button = document.getElementById("button");
var output = document.getElementById("output");
output.innerHTML = str;
button.addEventListener("click", function(e){
str = str.charAt(str.length - 1) + str.substring(0, str.length - 1);
output.innerHTML = str;
});
button{
display: block;
margin: 25px 0;
}
<button id="button">Click Me!</button>
<label id="output"></label>
It is, in fact, a scoping issue. Your counter in inside the function, so each time the function is called, it gets set to 0. If you want a counter that is outside of the scope, and actually keeps a proper count, you will need to abstract it from the function.
If you want to keep it simple, even just moving clickCount above the function should work.
I do not know if it's an issue of scope
Yes, it is an issue of scope, more than one actually.
How?
As pointed out by #thesublimeobject, the counter is inside the function and hence gets reinitialized every time a click event occurs.
Even if you put the counter outside the function, you will still face another scope issue. In the else part of the function, you are manipulation a variable (newString) you initialized inside the if snippet. Since, the if snippet didn't run this time, it will throw the error undefined. (again a scope issue)
A fine approach would be:
take the counter and the defaultString outside the function. If the defaultString gets a value dynamically rather than what you showed in your code, extract its value on page load or any other event like change, etc. rather than passing it inside the function.
Do not assign a new string the result of your manipulation. Instead, assign it to defaultString. This way you probably won't need an if-else loop and a newLastChar to take care of newer results.
Manipulate the assignment to the element accordingly.
You can use Javascript closure functionality.
var scrollString = (function() {
var defaultString = "Learning to Code Javascript Rocks!";
return function() {
// convert the string into array, so that you can use the splice method
defaultString = defaultString.split('');
// get last element
var lastElm = defaultString.splice(defaultString.length - 1, defaultString.length)[0];
// insert last element at start
defaultString.splice(0, 0, lastElm);
// again join the string to make it string
defaultString = defaultString.join('');
document.getElementById('Result').innerHTML = defaultString;
return defaultString;
}
})();
Using this you don't need to declare any variable globally, or any counter element.
To understand Javascript Closures, please refer this:
http://www.w3schools.com/js/js_function_closures.asp

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.

how do I pass count integer into a function?

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.

Finding value from a hidden field

I am adding value in my webpage as hidden like this:
cell.append('<input type="hidden" class="isTestValue" value="' + bill.IsTestBill + '">');
Now I wrote to get this value:
function getIsTestId(billIndex) {
var selectedRow = getSelectedRow(billIndex);
var lastCol = jQuery(selectedRow).find('TD:last');
return (lastCol.find('INPUT:hidden.isTestValue).val());
}
However, in my function when I am calling this getIsTestId:
var testId= getIsTestId(billIndex);
In testId the value is undefined. What am I doing wrong here?
PS: How should I check my isTestValue in immediate window?
You are missing a single quote in this line return (lastCol.find('INPUT:hidden.isTestValue).val());, try this.
return lastCol.find('input.isTestValue').val()
Looks like a minor typo, missing semicolon, in return statement, there might be other issues, but try this first...
function getIsTestId(billIndex) {
var selectedRow = getSelectedRow(billIndex);
var lastCol = jQuery(selectedRow).find('TD:last');
return lastCol.find('INPUT:hidden.isTestValue').val();
}
You have an unclosed quotation in this line:
lastCol.find('INPUT:hidden.isTestValue');
And as another answerer pointed out, I think it's supposed to be:
lastCol.find('input.isTestValue').val();

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