jquery - click on children not working if dynamically created [duplicate] - javascript

This question already has answers here:
jquery click event not firing on dynamically created div
(3 answers)
Closed 8 years ago.
I created a button tag inside my javascript
value = '<button id="structure_' + arrayCodStructure[j] + '" class="ui_btn" >' + arrayCodStructure[j] + ' </button><br></br>';
and then appended to an existing div this way:
$("#listContent").append(value);
My purpose is to get button's id when I click on the specific and tried the below code with no luck.
$("#listContent.ui_btn").bind("click".function() {
var id = $(this).Attr('id');
alert("id: " + id);
}
Any solution?
selector on #listContent works but it is not what I need.

Try to use event-delegation at this context and the selector that you have used is also wrong,
$("#listContent").on('click',".ui_btn" ,function() {
var id = this.id;
alert("id: " + id);
}

Related

Jquery: Getting the id of an html element: why one solution works and the other don't

I am referencing one element on an index page hidden initially and then showed with jquery on an index.html page. Can't explain why the first ones doesn't work, even if it should, but the last one does. I am getting the id of a pressed button "id='edit1'...2...3..etc" Thank you!
//why this doesn't work and the next one does???
/*$('.edit-btn').click(function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
$('.edit-btn').on('click', function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
*/
var id;
$("body").on("click",".edit-btn",function(){
id = (this.id).replace("edit","");
UPDATE:
The containers are hidden and shown using this function:
function hideWindowsAndShowOneWindow(sWindowId) {
$('.wdw').hide(); //fadeout 500
$('#' + sWindowId).show(); // fade in 500
}
So the div container, I am trying to reference by id was hidden after the page was loaded or maybe before the page is loaded. My guess is after the page is loaded...
The HTML:
<div class="wdw" id="wdw-events">
<h4>Events text</h4></br>
<div id="content"></div>
<h4>Edit Events</h4></br>
<div>
</div>
It is added/injected after the page was loaded with this js script, but still what has the last method special, just referencing through the document down to the id attribute of the button:
finalEventsLS.forEach(function (item) {
var date = item.date.day + "/" +item.date.month + "/" + item.date.year;
$('#content').append("<ul><li>" +
"Event nr.: " + item.id + " " +
"Name: " + item.name + " " +
"Topic: "+ item.topic + " " +
"Speaker: "+ item.speaker + " " +
"Date: " + date + " " +
"</li><button class='edit-btn' id='edit" + item.id + "'>Edit</button>
</ul>");
})
It's hard to tell, since you've only shared your jQuery. Update with your HTML please.
If you are referencing an element which was added to the DOM after the initial page load, .click will not work, because it only looks for elements initially loaded into the DOM. Instead, you would use the .on method, which looks for elements added to the DOM both before and after initial load.
UPDATE:
I should have looked closer. The second snippet of code that didn't work, but used the .on method, most likely didn't work because you are still trying to access the .edit-btn element, which at this point I'm assuming was added after page load. The code snippet that does work, is accessing the body element first. I will try to find and update with a better explanation, but the .on method still needs to find a element that existed in the DOM initially. From there, it can climb down the tree to find .edit-btn element.

How to find class name or id name of any element on a page? [duplicate]

This question already has answers here:
How do you get an ID of a clicked div element in JavaScript?
(2 answers)
Closed 6 years ago.
I want to get the name of id and class of any element and if it does not have any id or class then it should return null.
document.addEventListener('click',function(ele){
});
I have used this code to get the element clicked by the user.
How to get the id or class name if present using this "ele" element ?
how to get the id or class name if present using this "ele" element ?
document.addEventListener('click',function(ele){
alert("id is " + this.id );
alert("class is " this.className);
});
but this event is on the document, you won't get individual ids.
For that you need to bind an event to all elements of the document
var allElements = document.querySelectorAll("*");
for ( var counter = 0; counter < allElements.length; counter++)
{
allElements[counter].addEventListener('click',function(ele){
alert("id is " + this.id );
alert("class is " this.className);
});
}
if you want to use the JS way then you can do :
document.addEventListener('click',function(event){
var id =event.target.id;
var className=document.getElementById(id).getAttribute("class");
alert(id);
alert(className);
});
If you want to go with Jquery way : then
$(div).click(function(event){
alert($(this).attr("class"));
alert($(this).attr("id"));
});

Calling class attribute not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
I want to create after every container a click function. It had worked but not anymore. When I want to create the event, he don't recognize the container because in debugger I can see he's going over the box of code.
// Decide list order, load the thumbnail for each publication.
var place = "first";
$('#archive').prepend('<div class="container" id="'+entry.publicationID+'"></div>');
$('.container:' + place).append('<div class="thumb"></div>');
$('.thumb:' + place).css("background-image", 'url(' + entry.thumbnailURL + ')');
$('.thumb:' + place).css("filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
$('.thumb:' + place).css("-ms-filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
// Load the publication title below each thumbnail.
$('.thumb:' + place).after('<div class="title"></div>');
$('.title:' + place).append(entry.publicationName);
// Load the publication startsdate & enddate.
$('.title:' + place).after('<div class="date"></div>');
$('.date:' + place).append(sdate + " tot " + edate);
// Set up publication links.
$('.container:' + place).click(function(){
loadPub(entry.publicationID, entry.publicationName);
setActive(entry.publicationID);
//Change css of current element
});
http://api.jquery.com/on/ this will help you. Basically attach the click on the outer container of the div or box you dynamically create and check the target which is done by "on" api in jQuery
If you are loading these elements dynamically, you'll want to use the .on and delegate events so that elements loaded after the DOM has loaded will know to attach click handlers.
Below is an example of me using the .on(). I declare my parent container in the selector and the specific elements I want to delegate event listeners to. In this case, I can specify the pseudo-class :first and jQuery is smart enough to know to only do it to the first element.
$(document).ready(function(e) {
for (var i = 0; i < 10; i++) {
$('#container').append('<div class="element">Element ' + i + '</div>');
}
$('#container').on('click', ':first', function(e) {
alert('hello! this should only work on the first element!');
});
});
.element {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>

How to remove an element inside a div in jquery [duplicate]

This question already has answers here:
How can I remove a child node in HTML using JavaScript?
(9 answers)
Closed 8 years ago.
Um trying to remove an HTML element by JQuery as follows
$('#' + divId + ' .settings_class').remove('.print_settings');
This does not throw an error or remove the html element.
but the selector correctly retrieves the element.
$('#' + divId + ' .settings_class .print_settings');
How to remove an element inside a div by its class as follows?
$('#' + divId + ' .settings_class').find('.print_settings').remove();
If $('#' + divId + ' .settings_class .print_settings'); retriving correct element then use remove() on it! like
$('#' + divId + ' .settings_class .print_settings').remove();

remove select, from cloned element [duplicate]

This question already has answers here:
How to remove the selected element during a clone() operation
(2 answers)
Closed 8 years ago.
I have this js code to add (clone) and delete an element.
$('#btnAdd1').click(function (event) {
var num = $('.linguas').length;
var newNum = new Number(num + 1);
var newElem = $('#input_' + num).clone(false).prop('id', 'input_' + newNum);
newElem.children(':text').val('');
$('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
$('#btnDel1').prop('disabled', '');
if (newNum == 4) $('#btnAdd1').prop('disabled', 'disabled');
});
However, i want to remove the select="select" attribute, cloned from previous element.
I am trying something like this, but didn't work:
$('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
demo here
thanks
Try this alone:
$('option:selected', newElem).prop("selected", false);
Your code:
$('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
put the cloned select after the original, but then you searched for selected options using find on your original select. find searches children. The cloned select is now a sibling of the original not a child.

Categories

Resources