How to attach click event on dynamically appended inner elements? - javascript

I have a series div elements appended to a parent div.
Attaching click event binds on parent element.
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>"+j+"</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>
I need to know which appended div is clicked.

You can use the index() method
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>j</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:"+$(this).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

To get a reference to the element which raised the event use the this keyword in the event handler. To retrieve its index, you can use jQuery's index() method.
Also note that your logic can be made more succinct by appending all the HTML in one operation and using a single delegated event handler. Try this:
var elements = (new Array(10)).fill('<div class="aClass">j</div>');
$(".wrapper").append(elements).on('click', '.aClass', function() {
console.log(`index of element is: ${$(this).index()}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

You can append and attach an event on every iteration instead of at the end.
for (let j = 0; j < 10; j++) {
const element = $("<div class='aClass'>j</div>");
element.click(() => foo(j));
$(".wrapper").append(element);
}
function foo(index) {
alert("index of element is: "+index);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

If you're using jquery and you want to append a bunch of <div>s to a wrapper and have a click event on each, instead of creating a brand new event for each of those <div>s I would use event delegation and attach the event to the parent $('.wrapper'), then catch the event in the children. It would be something like this.
for (var j = 0; j < 10; j++) {
$('.wrapper').append($(`<div class="aClass">${ j }</div>`));
}
$('.wrapper').on('click', function(e) {
const target = $(e.target);
if (target.hasClass('aClass')) {
console.log(target.index());
}
});

function foo() {
alert("index of element is:" + $(this).text() + "-" + $(this).index());
}
var element = "";
for (var j = 0; j < 10; j++) {
element = element + "<div class='aClass'>j</div>";
}
$(".wrapper").append(function() {
return $(element).click(foo);
});
function foo() {
alert("index of element is:" + $(this).text() + "-" + $(this).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

You can use an anonymous function to pass this object to the function so that you can use .index() to find the position:
var element = "";
for( var j = 0; j < 10; j++){
element = element + "<div class='aClass'>"+j+"</div>";
}
$(".wrapper").append(function() {
return $(element).click(function() {foo(this)});
});
function foo(el){
console.log("index of element is:", $(el).text() + ' at index ' + $(el).index());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

You can append() inside the loop. And wrap foo inside wrapper and pass it to click.
var element = "";
const wrapper = $(".wrapper");
for(let j = 0; j < 10; j++){
element = "<div class='aClass'>j</div>";
wrapper.append(function() {
return $(element).click(() => foo(j));
});
}
function foo(index){
alert("index of element is:" + index);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper"></div>

Related

Click in JS loop undefined

I have an interation loop on which I need to click on every element:
var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i += 1) {
i.click(function() {
console.log("Clicked")
});
}
I get i.click is not a function error. ¿What am I missing?
Thanks!
i is the index, not the element. This is how you would fix your code:
var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i += 1) {
spans[i].click(function() {
console.log("Clicked")
});
}
But 'click' also doesn't take a callback. This is how your code should look like in 2022:
const spans = document.getElementsByClassName('span')
for (const span of spans) {
span.click();
console.log("Clicked")
}

How do I create different button for each item in an array / JavaScript

Here's my code:
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML = "<button>" + never[i] + "</button>";
}
}
I have a button in my HTML that invokes this function but it only creates a button for the last item (7). How can I create a different button for each one of the items in the array? Any help is appreciated.
The best way is to append created buttons in container.Each by each
var never = [1,2,3,4,7];
function please () {
var more=document.getElementById("more");
for (var i = 0; i < never.length; i++) {
var butt=document.createElement("button");
butt.innerHTML=never[i];
more.appendChild(butt);
}
}
By appending to innerHTML instead of assigning, like
var never = [1,2,3,4,7];
function please () {
for (var i = 0; i < never.length; i++) {
document.getElementById("more").innerHTML += "<button>" + never[i] + "</button>";
}
}
please();
<div id="more">
</div>

Returning html code in javascript

I want to print html code in Javascript code.
I want to open and close the bottom line of five li tags. How can I do this with a for loop
jQuery(document).ready(function () {
InsertLi();
});
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").html(codeBlock);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
You need to use append function instead. html function every time overrides your html content with the new content and you get only the last one. Also create your string with 5 li-s and then call the append at the end to work with DOM one time and have more performance.
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += ' <li>' + i + '</li>';
}
$(".bildirimMetin").append(codeBlock);
}
jQuery(document).ready(function () {
InsertLi();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin"></ul>
If you have only one item with bildirimMetin class, it will be better to use id instead of class.
Well, another solution, close to your code, with html, store all strings in your variable via += then you must define your variable before for loop also move your html after it. Your current code not working because it just store last string not all.
InsertLi();
function InsertLi() {
var count = 5;
var codeBlock = '';
for (var i = 0; i < count; i++) {
codeBlock += '<li>' + i + '</li>';
}
$(".bildirimMetin").html(codeBlock);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>
you had a couple issues. One was overwriting the inner HTML instead of appending. The other was a syntax issue.
function InsertLi(){
var count = 5;
for (var i = 0; i < count; i++) {
var codeBlock = ' <li>' + i + '</li>';
$(".bildirimMetin").append(codeBlock);
}
}
jQuery(document).ready(function () {
InsertLi();
}
);

Children loop html append into parent loop inserted div by javascript

The loop working but don't getting class as a selector from parent loop generated div...
var parentdiv = $(".pDiv");
for (i = 0; i < 3; i++) {
$(parentdiv).append("<label class="
addLabel ">" + i + "</label>"); // parent loop add
for (j = 0; j < 3; j++) {
$(".addLabel").append("<label class="
addLabel2 ">" + j + "</label>"); //children loop in parent class
}
}
First of all, your text has too many mistakes and it's hard to understand what exactly is the problem.
Secondly - your string in append() function is not concatenated properly as addLabel doesn't seem to be a variable. Try this:
$(parentdiv).append("<label class='addLabel"+ i +"'></label>") and
$(".addLabel").append("<label class='addLabel"+ j +"'></label>");
The problem solved the children loop :
//children loop start
for (var c = 0; c < checkBoxs.length; c++) {
// Things[i]
console.log(c);
var multiInputs = $("#myframe1").contents().find(".div2"); // iframe parent div
var putIntoParent = $(multiInputs).children(); // selector as parent children
var getMultiInput = multiInputs.selector;
//$(multiInputs).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
var node = document.createElement('span');
//var inputPlace = document.querySelector('.inputField_add');
console.log(multiInputs)
// $(multiInputs).on("load", function() {
$(putIntoParent).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
// });
}

JQuery dynamically added button, text not in button

When I attempt creating buttons from jQuery, the text appears outside of the button element I created. I've tried creating each button individually and as a group, and neither method seems to work. What am I doing wrong?
<div id = 'output_div'></div>
var main = function(){
var selections = ['derp', 'herp', 'merp', 'foo'];
//individually creating each button
for(var i = 0; i < selections.length; i++){
$('#output_div').append("<input type='button'>" + selections[i] +
"</input>");
};
$('#output_div').append('<br><br>');
//buttons all created at the same time
var group_buttons = '';
for(var i = 0; i < selections.length; i++){
group_buttons += ("<input type='button'>" + selections[i] + "</input>");
};
$('#output_div').append(group_buttons);
};
$(document).ready(main);
https://jsfiddle.net/fjr56Lsj/4/
Another way to create a button using jquery would be as follows:
var dynamicButton = $('<button/>', {
text: selections[i],
id: 'dynamicButton_'+i
});
$('#output_div').append(dynamicButton);
Set the button text either as the value attribute of the <input>, or render the buttons as <button>:
$(function() {
var selections = ['derp', 'herp', 'merp', 'foo'];
for (var i = 0; i < selections.length; i++) {
$('#output_div').append("<input type='button' value='" + selections[i] + "' />");
};
$('#output_div').append('<br><br>');
for (var i = 0; i < selections.length; i++) {
$('#output_div').append("<button>" + selections[i] + "</button>");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'></div>
As input type button attribute , use value = selections[i] (keep Ur quotes careful)😉 else use button tag instead input element
The Button can be created in this fashion too:
$('<button/>', {
text: selections[i]
})
var main = function() {
var selections = ['derp', 'herp', 'merp', 'foo'];
//individually creating each button
for (var i = 0; i < selections.length; i++) {
$('#output_div').append($('<button/>', {
text: selections[i]
}));
};
$('#output_div').append('<br><br>');
};
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'>
</div>

Categories

Resources