Button created with jQuery/JS, don't react to click [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
jQuery click not working for dynamically created items [duplicate]
(8 answers)
Closed 7 years ago.
I'm trying create a list of Messages a user can type in an textarea on the site and delete any of them using a button he automatically creates with each message.
My idea is that I create a div in which I first put the message of the user in and then prepend the button with the same ID of the div; This way I call the ID of the button and remove all elements with the same ID.
<script>
var theButtonId = 1;
$(document).ready(function() {
$('#commentButton1').click(function() {
var toAdd = $("textarea#commentTextarea1").val(); //Content to add
var theId = "dieButtons"+theButtonId.toString(); //creating unique ID
// Adding first Div
$('#targetField').append(
$('<div />', {
id: theId,
}));
// Adding content
$('#'+theId).append(
$('<div />', {
text: toAdd
}));
//(-----1-----)Adding Button
$('#'+theId).prepend(
$('<button />', {
type: 'button',
id: theId,
class: 'commentButton2',
text: "-"
}));
theButtonId++;
});
});
//Button Command
$(document).on("ready", function(){
//(-----2-----)
$('.commentButton2').on("click", function(){
var thisId = $(this).attr("id");
$("#"+thisId).remove();
});
});
</script>
It perfectly lists the elements in the #textfield
I added a button directly in my HTML code which deletes certain divs, as well as itself using the code above. This is why I know that the Problem is that the created Buttons at (-----1-----) don't react to the command in (-----2-----)
I already tried to create an Input of type button and put a .click function instead of .on("click", [...]).

$(document).on('click', '#buttonid', function() {
});
Use event delegation on dynamically created elements
DOCUMENTATION

Working fiddle
Try to use :
$('#targetField').on("click",'.commentButton2', function(){
Instead of :
$('.commentButton2').on("click", function(){
It should work.

Related

How to auto update child input jquery [duplicate]

This question already has answers here:
How to select an element inside "this" in jQuery?
(2 answers)
Closed 2 years ago.
Hi I'm trying to use jquery to autoupdate an input field which is wrapped around a contenteditable div. There are multiple such divs that is generated by the backend code, and I would like each input to update only if its parent's div's contenteditable has been updated. The html looks something like this:
<div class="to-change" contenteditable="true">
Text that can be edited
<input name="autoupdate">
</div>
I have tried using the following jquery code:
<script>
$( document ).ready(function() {
console.log( "ready!" );
$('.to-change').on("keyup", function() {
var input = $(this).text()
$('input:first-child').val(input)
})
});
</script>
The thing is when I try to change the text, every other such divs' input field will also be updated with the same text. How do I change the jquery code such that the input field will always take reference from its own parent div?
Thanks!
You can Select that element like this:
$(document).ready(function () {
console.log("ready!");
$('.to-change').on("keyup", function () {
var input = $(this).text()
$('.to-change > :first-child').val(input);
});
})
Or:
$(document).ready(function () {
console.log("ready!");
$('.to-change').on("keyup", function () {
var input = $(this).text()
$('.to-change > input').val(input);
});
})
">" Used for selecting Direct childs of an Element, You can find More about this selector in https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

Event listener gets removed on post method [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
After I click on a th with the class database-header, my table gets sorted via the post method, but for some reason the click event listener gets removed, so when I click again on a different database-header, nothing happens. What em i doing wrong ?
$(function () {
var user = $('#user');
var databaseHeader = $('.database-header');
var tableContainer = $('.table-container');
var databaseHeaderValue;
var url = './php/table.php';
databaseHeader.click(function () {
/* Checks for the user login div */
if (user.closest('html').length){
databaseHeaderValue = $(this).html();
$.post(url, {'sort' : databaseHeaderValue}, function (data) {
tableContainer.html(data);
});
}
});
});
Try changing your jquery click like below:
var user = $('#user');
var databaseHeader = '.database-header';
var tableContainer = $('.table-container');
var databaseHeaderValue;
var url = './php/table.php';
$(document).on('click', databaseHeader, function () {
/* Checks for the user login div */
if (user.closest('html').length){
databaseHeaderValue = $(this).html();
$.post(url, {'sort' : databaseHeaderValue}, function (data) {
tableContainer.html(data);
});
}
});
Do you only refresh a part of the page? After a DOM element is added dynamically, you cannot grab it with a jquery selector.
try
$(body).on("click", ".database-header",function(){
etc..
}

register click event on generated html table [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I am generating html table on ajax callback like
...
success: function (data) {
if (data != undefined) {
var table = $("<table id='carTable' />").addClass("table table-striped table-bordered table-condensed");
var header = $("<thead/>").html("<tr><th>a</th><th>b</th><th>c</th><th>d</th><th>e</th><th>f</th><th>g</th>");
table.append(header);
for (var i = 0; i < data.length; i++) {
var row = $("<tr/>");
row.append($("<td id='carId'/>").html(data[i].Id));
row.append($("<td id='name'/>").html(data[i].Name));
row.append($("<td/>").html(data[i].Color));
row.append($("<td/>").html(data[i].Doors));
row.append($("<td/>").html(data[i].Fuel));
row.append($("<td/>").html(data[i].Injection));
row.append($("<td/>").html(data[i].Desc));
table.append(row);
};
$("#carsTable").html(table);
}
},
...
On same page using javascript I want to recognize click event on table row of this carTable generated snippet.
$('#carTable tr').on('click', function (e) {
console.log('click!');
});
Is this because of generated html in the callback and if it is how to solve this?
$(document).on('click', '#carTable tr', function(e) {
console.log('click!');
});
Will trigger the callback function on every click that matches the selector in the second argument, no matter if it was there from first rendering the page, or added later via JavaScript.
Please note, however, that this does come with a price of internally triggering on every single click anywhere on the document and jQuery will internally check if the condition is matched.
So even better would be to delegate the click event to the table instead:
$('#carTable').on('click', 'tr', function(e) {
console.log('click!');
});
Which is essentially the same, just not binding to every single click on the whole document.

I want to make a parameterized function in javascript in which on button

I want to make a parameterized function in javascript
in which on button click an HTML <label> tag should be append with unique id every time I click on button with a parameter value.
If I understood your question, you are trying to bind a click event to a <label> tag. So just find it on the dom
var myLabel = document.getElementById('--your label id--');
And then call
myLabel.addEventListener('click', function() {
// your code goes here
console.log('hey there!');
});
If you happen to be using jQuery, you can use a cleanner syntax:
$('#label').on('click', function () {
// you can even fetch data from the label:
var title = $(this).attr('title');
var customData = $(this).data('customData');
/* ... */
});

Dynamic click event for buttons [duplicate]

This question already has answers here:
Jquery dynamic button : how to bind to exisitng click event by class
(2 answers)
Closed 9 years ago.
I have a button which calls a function via data-bind and generates a new button.
self.submitNewPopUp = function(data, event) {
var butnId = event.srcElement.form.id.replace('style-', '');
var styleButton = $('<input/>').attr({type: 'button', value: data.styleData, id: butnId});
styleButton.onclick = function() {
alert("blabla");
};
$("#showButtons").append(styleButton);
$('#' + event.srcElement.form.id).hide();
};
But the new button has no click event. How to do it?
You'd assign a click event listener to an ancestor of the button using jQuery's on() method. For instance, if your markup was:
<div id="showButtons">
<input type="button" />
</div>
You'd use:
$('#showButtons').on('click', 'input[type=button]', function() { ... });
styleButton button is a jQuery object, not a dom element so it does not have a onclick property. You need to use the click(function(){}) event registration method to register the event handler
styleButton.click(function() {
alert("blabla");
});
Use jquery.on() for the dynamic created elements
$("#div").on("click", "button", function(event){
alert($(this).text());
});

Categories

Resources