My Question
I am having trouble finding how to place a for loop inside a jQuery append method. Should it be a strong, should it be just there, how do I format the code so it works?
My Code
window.onload = function () {
$(function () {
$('#li22').append($('<table/>').append(for (var i = 0; i <= 3; i++) {'$('#li22').append($(""));'}));
});
}
Firstly, don't put a for loop directly in the append() method. Secondly, don't put a document.ready event handler inside a window.onload handler - it's pointless.
Also, it's not exactly clear what you're trying to achieve. You're appending a table to #li22, then appending nothing to #li22 and returning that to the table...? As such the below is a general guide on how to use append() properly.
append() accepts a either string, so you should put the for outside the append(), like this:
$(function () {
for (var i = 0; i <= 3; i++) {
$('#li22').append($('<table/>'));
}
});
Alternatively you can provide a function to append() which returns the HTML to be appended. You can put the for in there:
$(function () {
$('#li22').append(function() {
var html = '';
for (var i = 0; i <= 3; i++) {
html += '<table></table>';
}
return html;
});
}
});
You can not execute code inside of a function's argument. Therefor, the code must be formatted like:
window.onload = function () {
$(function () {
var tableTag = $('<table><table/>');
$('#li22').append( tableTag );
for (var i = 0; i <= 3; i++) {
$( tableTag ).append( "" );
}
});
}
Try Like this .
$(document).ready(function () {
var string="<table>";
for (var i = 0; i <= 3; i++)
{
string += "what you need";
}
string +="</table>"
$('#li22').append(string);
});
Related
I want to change the text inside of an element for dynamically created elements. i = 2 because that's Why is it not working?
var loanName = function() {
for(var t=1; t < i; t++) {
$('body').on('keyup', '.loanNameV'+t, function () {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
};
$('body').on('keyup', '[class^="loanNameV"]', function () {
var numbesideclass = ($(this).attr('class').split('loanNameV'))[1];
var loanN = $(this).val();
$('.nameLoan'+numbesideclass).text(loanN);
});
Note: this code will work if you don't have another class for loanNameV elements like class="loanNameV1 anotherclass anotherclass" in this case this code will not work as expected
I am a beginner in JavaScript and jQuery, and I would like to have an idea to how to proceed with this part of a code,
I have a function with a callback, for example:
myFunc(elem, callback) {
$(elem).fadeIn(function(){ callback(); });
}
and I want to run this function for elements that are in an array:
elems = ['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'];
but, I want to execute this function for each element of the array, one by one through the callback.
eg. once #elem1 has fadein, it must fadein second element ..etc
now I proceed like this:
I have tried to do a for loop, but they are executed in the same time.
for (i = 0; i < elems.length; i++) {
myFunc(elem[i], function(){
if (elem[i+1]) {
myFunc(elem[i+1]);
}
});
}
So how would you proceed?
Do like this, A recursive solution for your problem,
function myFunc(elems, cnt)
{
if(cnt > (elems.length - 1)) { return; }
$(elems[cnt]).fadeIn("slow", function(){ myFunc(elems , ++cnt); });
}
myFunc(['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'], 0);
DEMO
Update on link:
http://jsfiddle.net/kuw6tt92/1/
function fadeIn(selectors) {
var elements = Array.prototype.slice.call($(selectors));
function fade() {
jQuery(elements.shift()).fadeIn("slow", fade);
}
fade();
}
fadeIn("div");
try
var elems = ['#elem1', '#elem2_3', '#elem4_5', '#elem3', '#elem_five'];
var len = elems.length;
function myFunc(index) {
$(elems[index]).fadeIn(function () {
if (len > ++index) myFunc(index);
return;
});
}
myFunc(0);
DEMO
So I have this eventListner that calls an Class, works like a charm but only once since inte call the add class with index 0.
Im trying to create a loop that will call every add class inside the script, but i cant get loop...
This is the event listner without the loop
var AddEvent = "add";
var addClass = document.getElementsByClassName(AddEvent)[0]
addClass.addEventListener("click", addDiceEvent, false);
function addDiceEvent() {
dicesides_funcfunc();
}
And this is what Im trying to create.
function AddDice(){
for (i = 0; i < 5; i++) {
var addClass = document.getElementsByClassName("add");
addClass.addEventListener("click", addDiceEvent, false);
function addDiceEvent(){
dicesides_funcfunc();
}
}
} AddDice();
Any ideas ?
Hope this work.......
var addClassArr= document.getElementsByClassName(AddEvent);
for (var x in addClassArr)
{
var addClass = addClassArr[x];
addClass.addEventListener("click", addDiceEvent, false);
}
function addDiceEvent() {
dicesides_funcfunc();
}
You need to create new skope in for loop, try this:
function AddDice(){
for (i = 0; i < 5; i++) {
(function(){
var addClass = document.getElementsByClassName("add");
addClass.addEventListener("click", function(){
dicesides_funcfunc();
}, false);
})();
}
}
Preamble: I'm Italian, sorry for my bad English.
This is my problem:
I want to assign a function to a set of buttons.
I need to send a parameter to the function.
this is the code that I've tried:
function test(atxt) {
var buttons = $('.tblButton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onClick(sayHello(atxt));
}
}
function sayHello(txt){alert('hello' + txt)};
...getting the following error:
Uncaught TypeError: Object #<HTMLButtonElement> has no method 'onClick'
can you tell me where I went wrong and how can I fix it?
EDIT: I need iteration because I need the 'id of the button as a parameter of the function so i need to do buttons[i].onClick(sayHello(buttons[i].id))
buttons[i].onClick(sayHello(atxt));
Supposed to be
$(buttons[i]).on('click', function() { sayHello(atxt) });
If you want to get the current button id then I think you are looking for this..
for (var i = 0; i < buttons.length; i++) {
$(buttons[i]).on('click', function() { sayHello(this.id) });
}
If you want to iterate through all of the buttons then you have to do that with .each() handler of the jquery:
$(function(){
$(".tblButton").each(function () {
$(this).click(function(){
alert($(this).attr('id'));
});
});
});
checkout the jsbin: http://jsbin.com/usideg/1/edit
Would this not work for your example: Do you have another reason for the iteration?
function test(atxt) {
$('.tblButton').on('click',function(){sayHello(atxt);});
}
function sayHello(txt){alert('hello' + txt)};
OR optionally if the elements are static and present:
function test(atxt) {
$('.tblButton').click(function(){sayHello(atxt);});
}
function sayHello(txt){alert('hello' + txt)};
Alternate approach: just change
to this style:
var txt = "fred";
var atext = "hello" + txt;
function sayHello(atext) {
alert(atext);
}
$('.tblButton').on('click', function() {
sayHello(atext);
});
//below here just to demonstrate
$('.tblButton').eq(0).click();//fires with the fred
txt = "Johnny";// new text
atext = 'hello' + txt;
$('.tblButton').eq(1).click();//fires the Johnny
see it working here:
http://jsfiddle.net/dFBMm/
SO based on your note:
this markup and code:
<button class="tblButton" id="Ruth">Hi</button>
<button class="tblButton" id="Betty">Hi again</button>
$('.tblButton').on('click', function() {
alert("Hello "+$(this).attr("id"));
});
$('.tblButton').eq(0).click();//fires with the Ruth
$('.tblButton').eq(1).click();//fires the Betty
http://jsfiddle.net/dFBMm/1/
I have in Javascript:
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
}
How can I continue in jQuery like:
$(function() {
$(vst).'click': function() {
....
}
}
NO, like this instead
$(function() {
$(vst).click(function() {
....
});
});
There are other ways depending on your version of jquery library
regarding to this, your vst must need to be an object which allow you to click on it, and you assign a class or id to the object in order to trigger the function and runs the for...loop
correct me if I am wrong, cause this is what I get from your question.
$(function() {
$(vst).click(function() {
....
}
})
You can use any string as element selector param for jQuery.
Read the docs for more information.
http://api.jquery.com/click/
http://api.jquery.com/
You can pass a String in a variable to the $() just the way you want to do it.
For example you can do:
var id = 'banner';
var sel = '#'+id;
$(sel).doSomething(); //will select '#banner'
What's wrong is the syntax you are using when binding the click handler. This would usually work like:
$(sel).click(function(){
//here goes what you want to do in the handler
});
See the docs for .click()
Your syntax is wrong, but other than that you will have no problem with that. To specify a click:
$(function() {
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
$(vst).click(function (evt) {
...
});
}
})
Note that since vst is changing in the loop, your event code should also be placed in the loop.
EDIT: Assuming you want the same thing to happen for each image and each div, you could also do something like this:
$(function () {
function imgEventSpec($evt) {
// image clicked.
}
function divEventSpec($evt) {
// div clicked.
}
for (var idx = 0; idx < img_arr.length && idx < div_arr.length; idx ++) {
$("#" + img_arr[idx]).click(imgEventSpec);
$("#" + div_arr[idx]).click(divEventSpec);
}
});