for loop inside jquery function - javascript

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
}

Related

how can I append some html code using js several times

Hy guys, I have the following problem...
I need to draw in some cases (ex. when edit, save, update, etc) a defined html code (is the one at the end of the post) using js but I don't want to explicitly add the whole code every time i need it, so I'm wondering... ¿Is there a better way than adding it to a var and then .append or .html the code? instead of building the code every time I want to make it into an object oriented approach with properties and building it when needed, is there a way?
This is the code
for (var i = 1; i <= lineas; i++) {
c += "<div class='row'><section>some html for example</section></div>";
c += "<div>some other stuff</div>";
}
$('#res').append(c);
By a better way to do this... I mean... or I'm looking for, some kind of object oriented way to doit, hope you guys get it.
Regards!
If you mostly use the same formats, you can write an object that will define some commonly-used (in your judgement) helpers:
var helper = {
sectionInDiv: function(divClass, sectionText) {
var result = "<div class='" + divClass +"'><section>" + sectionText +"</section></div>";
return result;
},
divOnly: function(text) {
var result = "<div>" + text + "</div>";
return result;
},
repeat: function (n, htmlText){
var result = "";
for (var i = 1; i <= n; i++) {
result += htmlText;
}
return result;
}
...
}
and then use it:
var htmlToRepeat =
helper.sectionInDiv("row", "some example text") +
helper.divOnly("some more text");
helper.repeat(10, htmlToRepeat);

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.

JQuery for loop stuck at last index [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
jQuery Looping and Attaching Click Events
(4 answers)
Closed 9 years ago.
I have function process_row that appends tags to html, and those tags are chained to a function upon clicked. (in this case, simply alert(i), its position in the result array).
But however, upon being clicked, the newly generated alerts the length of the entire result array. I have tried many, many changes to try and make it work, but it doesn't.
Strange thou, fab_div.attr("id", result_data[0]); works fine !! In Chrome inspect element the id tags are displayed as they are, but the click function points everything to the last element in the array.
for example, if I do, fab_div.click(function () { alert(result_data[0]) });, I get the name of the LAST element in the array, doesn't matter which element was clicked.
can anyone please explain to me... WHY??
I think it may have something to do with $("<div>") where JQuery thinks it's the same div that it's assigning to. Is there any way around this? The 's are generated dynamically and I would not want to let PHP do the echoing. Plus the content may be updated realtime.
Example dataset :
Smith_Jones#Smith#Jones#janet_Moore#Janet#Moore#Andrew_Wilson#Andrew#Wilson
After many, many changes, still not working:
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>");
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
fab_div.append(fab_text)
// fab_div.click(function () { alert(i) });
// ^ not working, try appending list of id's to id_list
id_list.push(result_data[0])
$('#ls_admin').append(fab_div)
}
for(j = 0; j < id_list.length; j++){
$('#' + id_list[j]).click(function () { alert(j) })
}
}
}
Original Attempt:
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text).click(function () { alert(i) });
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
}
}
If you must use an alert, then you can encapsulate the click handler in a self executing function and pass the index to it. Like,
(function (index) {
fab_div.click(function () {
alert(index);
});
})(i);
Although, this is not a clean way to do it. Otherwise, if you are looking to just manipulate the div element is any way, then adding any method directly will also work. Like,
fab_div.click(function () {
alert($(this).attr('id'));
});
You can refer a jsFiddle here
Wonky Solution, but it worked! Haha! Big thanks to Kevin B.
function process_row(data){
result_array = data.split("#");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text);
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
$("#ls_admin").children(this).each(function( index ) {
$(this).append($(this).click(function () { alert($(this).text()) }));
});
}
}

Javascript innerHTML out of scope issue?

I was wondering why the following jsfiddle does not work. And if there is anyway for it to work. Any ideas would be appreciated. I would think since the html would include the variable name at the time, that it would work ... but it doesnt. Weird. I am using firefox, latest build.
What should happen: onclick should alert!
http://jsfiddle.net/VqA9g/125/
Your method call needs to quote the list_name.
Here's the edited script that works:
function example() {
for ( var i = 0; i < list.length ; i++ ) {
var list_name = list[i];
var div = document.getElementById('testing');
div.innerHTML += "<txt onClick=\"test('" + list_name + "');\">" + list_name + "</txt><br>";
}
}
With this little change, I can see the alerts working.
You forgot to enclose the words in quotes. So with your code it was passing as a variable, that was not defined. Here is an updated version:
http://jsfiddle.net/VqA9g/131/

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

Categories

Resources