Bind click event not work in dynamic created elements - javascript

I call call ajax and when success i build button elements.
Like this :
...
.done(function(data) {
$('#data-message').empty();
// console.log(data);
$('#total_notification_msg').html(data.total);
$.each(data.data, function(index, value) {
// console.log(value);
var redirectRead = '{{ route("adm1n.message.show", ":id") }}'
redirectRead = redirectRead.replace(":id", value.id);
var pesan = value.message.substr(0,100);
$('#data-message').append('<button id='reply' class='btn btn-default btn-xs' style='margin-top:5px;'>Reply</button>");
});
})
...
But, i can't add click event on #reply button.
I already using on or click event :
$(document).on('click', '#reply', function() {
alert('Reply here');
});
// or this ...
$('#reply').click(function() {
alert('Reply here');
});
But it still not works.
Please help, thank you ^^

You need to use quotes properly when creating elements using string.
$('#data-message').append('<button class="reply btn btn-default btn-xs" style="margin-top:5px;">Reply</button>");
And use Event Delegation using .on() delegated-events approach, when generating elements dynamically
$('#data-message').on('click', '.reply', function() {
alert('Reply here');
});
Since Identifiers must be unique, use class instead.

You need to change two things:
correct quotes.
change id to class.
$('#data-message').append("<button class='btn btn-default btn-xs reply' style='margin-top:5px;'>Reply</button>");
//-----------------change here-----------------------------------^^^^^
Because you are in loop and you are duplicating same ids.
change your event binding to class:
$(document).on('click', '.reply', function() {
alert('Reply here');
});

Related

query click event for buttons inside a foreach loop

I am populating a data-table from a model using a foreach loop:
#foreach(var item in Model)
{
<tr>
<td style="display: none">#item.Id</td>
<td>#item.Name</td>
<td>#item.Description</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default" data-dismiss="modal">Update</button>
<button type="button" data-id=#item.Id id="Delete" class="btn btn-danger" data-dismiss="modal">Delete</button>
</div>
</td>
</tr>
}
Each row of the table has an update and delete button.
I'm struggling to bind the buttons to a click event using jQuery.
Here is my script so far which is within the document ready function:
var table = $('#productTable').DataTable();
$('#productTable tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert(Product ID = ' + data[0] + ');
//Call delete function and pass in Id
});
This is understandably showing an alert anytime the user clicks the row. How to I get it to only fire when the delete button is clicked?
Thanks in advance for any help.
You can take doutriforce suggestion and bind the events to a class, for example:
$("#productTable tbody").on("click", ".btn-update", function() {
// Your update code here
// Use $(this) to access the button that triggered this event
}
$("#productTable tbody").on("click", ".btn-delete", function() {
// Your delete code here
// Use $(this) to access the button that triggered this event
}
I've used: $("#productTable tbody").on("click", ", function); because it also works for dynamically added elements (in this case, table rows).
Based on the documentation here, it looks like you need to edit the selector that you bind the click event too, like this:
$('#productTable button#Delete').on('click', function () {
var data = table.row(this).data();
alert(Product ID = ' + data[0] + ');
});
const medias = document.querySelectorAll('._23fpc');
for (let i=1; i<medias.length; i++) {
const media = medias[i];
const firstClickable = media.querySelectorAll('._1JX9L')[1];
if(firstClickable) {
window.setTimeout(() => firstClickable.click(), 50);
}
}
I edited the code copied from the internet, it kind of works
PS:I know nothing about coding

How can I set click function on my current element?

I am trying to dynamically set a click function on a role=button element I add from jQuery. Here is my code:
box_resources.forEach(function(box){
var title_button = '<a class="btn btn-primary btn-xs" style="margin:5px">' + title + '</a>';
var $list_item = $(title_button);
$list_item.click(function() {
console.log("hello");
});
$("#resources-master-list").append(title_button);
});
It seems this way does not work. Does anyone have any idea? Thanks!
Instead of adding a new click handler each time you add an item to the DOM, try using event delegation. To understand how this works, check out the link for more information.:
$(document).on("click", "[role='button']", function () {
alert("i'm clicked");
});

combining jquery click functions

I am quite new to jquery and was wondering if someone could recommend some ways I could combine these functions together so that the code would be more efficient and slimmed down. I basically have two click functions that do the exact same thing but are targeting two different buttons. Thank you.
$( ".step1 button" ).click(function() {
if ($(".step1 input").is(":checked")) {
$( ".step1").slideUp("slow",function(){
$(".step2").slideDown("slow");
});
} // end if
else{
$("div.error").remove();
$(".step1.step-heading").append("<div class='error'><i class='fa fa-exclamation-triangle'></i> Please make a selection before continuing</div>");
} // end else
})// end click function
$( ".step2 button" ).click(function() {
if ($(".step2 input").is(":checked")) {
$( ".step2").slideUp("slow",function(){
$(".step3").slideDown("slow");
});
} // end if
else{
$("div.error").remove();
$(".step2.step-heading").append("<div class='error'><i class='fa fa-exclamation-triangle'></i> Please make a selection before continuing</div>");
} // end else
})// end click function
You can access the DOM element tha trigger the event by using $(this) inside the vent handler.
So, you simply have to attach the same handler to several elements, and use $(this) inside the implementation of the handler.
$(".step1 button").add(".step2 button").click(function() {
// $(this) refered to the button tha triggered the event
}
To make easier to find the step number you can use a custom "data-" attribute, for example like this:
<button data-step-no="1">
You can get that attribute by using $(this).attr('data-step-no'), In fact, to add or substract, you need to parse it like this: var stepno = parseInt($(this).attr('data-step-no').
To select all the buttons wit a single selector you can use buttons like this:
<button data-step-no="1" class="step">
<button data-step-no="2" class="step">
Ans select them all in a single step:
$('button .step').click(...
Here is a simple refactor that will not require changes to HTML:
$('[class^="step"]').each(function(k, v) {
var $btn = $(v).find('button'),
$input = $(v).find('input'),
$next = $(v).next(),
$heading = $(v).find('.step-heading'),
error_html = "<div class='error'><i class='fa fa-exclamation-triangle'></i> Please make a selection before continuing</div>";
$btn.click(function(e) {
if ($input.is(':checked')) {
$(v).slideUp('slow', function() {
$next.slideDown('slow');
});
} else {
$('div.error').remove();
$heading.append(error_html);
}
});
});

Button does not call function when clicked

I'd like a function t run when a button is clicked. It works fine when I approach it like so in the html body
<div type="button" id="decline" class="btn btn-danger mrs"></div>
However, I need it to work within the below code block, which is within a underscore.js wrapper. At the moment the function won't execute using the below, I'd like to understand why? is the id in the wrong place?
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button"
id="decline"
class="btn btn-danger mrs">' +
'Decline' +
'</div>');
$('#containerFriendsPending').append(wrapper);
});
While the code solution you posted will work the first time:
$('#decline').click(function() {
Friendrequest_decline();
});
It will not work after the wrapper code is replaced, as per your answer. You must use .on() to delegate the event:
$(document).on('click', '#decline', function() {
Friendrequest_decline();
});
or
$('#containerFriendsPending').on('click', '#decline', function() {
Friendrequest_decline();
});
Eg:
$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})
Solved this myself.
The following needed to be added within the original question main code block
$('.decline').click(function() {
Friendrequest_decline();
});
So doing this works.
$('#containerFriendsPending').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<div type="button" id="decline" class="btn btn-danger mrs">' + 'Decline' + '</div>');
$('#containerFriendsPending').append(wrapper);
$('.decline').click(function() {
Friendrequest_decline();
});
});
As you didn't provide the code that launches the click event it's hard to debug, but I'm going to assume it's actually the most common mistake that causes this problem: You are binding the click event before the element actually exists. That way, the browser will not know the new element also needs the click event.
Example:
$('.test').click(someFunction);
$('body').append( $('<div class="test">Click me!</div>');
This will not work, because the click event is bound first and the element is created later.
The jQuery .on() function can handle that by also watching for new elements that are created in the DOM:
$('body').on('click', '.test', someFunction);
$('body').append( $('<div class="test">Click me!</div>');
Now it will run someFunction successfully.

Find Id of clicked button

I wanted to get the id of clicked button since i have 4-5 buttons on my form.
<button type="submit" style="height: 30px" id="btnHelp" name="btnHelp" onclick="ShowHelp(2);return false;">Help</button>
<button type="button" style="height: 30px" id="btnClose" name="btnClose" onclick="Close();return false;">Close</button>
<button type="button" style="height: 30px" id="btnSave" name="btnSave" onclick="Save();return false;">Close</button>
...............................
Whichever may be the button click, I just want to get id of that button.
$(function () {
var id = $(this).attr('id');
alert(id);
})
Also with
$("input").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
but i am getting the alert as undefined.
How can i get id of button clicked?
Please help me.
Try
:button Selector
Selects all button elements and elements of type button.
$(":button").click(function (event) {
var urlid = this.id;
alert(urlid);
});
Fiddle Demo
Problem
$("input") --> selects elements with tag input eg. <input type="text"/> but not <button> tag .
I'd try to replace this with the event triggerer.
var urlid = $(event.target).attr("id");
Also, probably your onclick function is preventing your script to be executed, because it's handling the click event, not letting your function do it.
I ditched the onclick attributes of buttons you have, and hooked click events to button rather than input, and it worked. So check whether you are connecting to the right element.
See example here.
<script>
jQuery(":button").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
</script>
Try this its work
very simply:
$("input").click(function (event) {
var urlid = this.id;
alert(urlid);
})
for button:
$("button").click(function (event) {
var urlid = this.id;
alert(urlid);
})
You might try use event passed as argument into any event handler instead of this for event.target is referring to element actually triggering your handler (being clicked) and event.delegateTarget being element handler has been attached to initially. In both cases you might have to use $() for using jQuery or simply stick with accessing .id in either case.
In your case this would be
$("input").click(function (event) {
var urlid = $(event.delegateTarget).attr('id');
alert(urlid);
});
to ensure handler is always accessing that it has been attached to, here.
Except for this quite simple scenario relying on this is sometimes trickier than using provided arguments.
EDIT : However, your case seems to be related to issues encountered by Tusha Gupta, for sure. Your buttons aren't "inputs" so that handlers are never attached, actually.
$(function () {
$("button").click(function () {
alert($(this).attr("id"));
});
});

Categories

Resources