How can I set click function on my current element? - javascript

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");
});

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

Bind click event not work in dynamic created elements

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');
});

jquery - link appended to table doesn't work

Hey guys I have some jquery code that adds a row to a table with a link to remove it and return it back to the select. Here's the code:
$('#addUser').on('click', function (e) {
var selectedUser = $('#Utilizadores option:selected').text();
$('#tabela > tbody:last').append('<tr id="'+selectedUser+'"><td>' + selectedUser + '</td><td><a id="removeUser" href="#" class="btn btn-default btn-xs"><i class="glyphicon glyphicon-remove"></i></a></td></tr>');
$("#Utilizadores option[value='" + selectedUser + "']").remove();
e.preventDefault();
});
It works! But now I want to do the reverse action of this. So I was just tying it out and not even the alert goes off. Here's the remove code:
$('#removeUser').on('click', function (e) {
alert('teste');
e.preventDefault();
});
The same id I gave to the <a> tag but still nothing gets called. I inspect the element and the id is corret and everything.
Does anyone know what the problem is?
To anyone who stumbles here and doesn't see the warning above!
You can check a Question for the same problem here
Try using the live() method
$('#removeUser').live('click', function (e) {
alert('teste');
e.preventDefault();
});

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.

Bypass onclick event and after excuting some code resume onclick

I have the below html button which have onclick event
<button onclick="alert('button');" type="button">Button</button>
and the following js:
$('button').on('click', function(){
alert('jquery');
});
After executing some js code by jQuery/Javascript, i want to continue with the button onclick handler e.g: jquery alert first and than button alert.
i tried so many things like "remove attr and append it after executing my code and trigger click (it stuck in loop, we know why :) )" and "off" click. but no luck.
is it possible via jQuery/javascript?
any suggestion much appreciated
Thanks
A little bit tricky. http://jsfiddle.net/tarabyte/t4eAL/
$(function() {
var button = $('#button'),
onclick = button.attr('onclick'); //get onclick value;
onclick = new Function(onclick); //manually convert it to a function (unsafe)
button.attr('onclick', null); //clear onclick
button.click(function() { //bind your own handler
alert('jquery');
onclick.call(this); //call original function
})
});
Though there is a better way to pass params. You can use data attributes.
<button data-param="<%= paramValue %>"...
You can do it this way:
http://jsfiddle.net/8a2FE/
<button type="button" data-jspval="anything">Button</button>
$('button').on('click', function () {
var $this = $(this), //store this so we only need to get it once
dataVal = $this.data('jspval'); //get the value from the data attribute
//this bit will fire from the second click and each additional click
if ($this.hasClass('fired')) {
alert('jquery'+ dataVal);
}
//this will fire on the first click only
else {
alert('button');
$this.addClass('fired'); //this is what will add the class to stop this bit running again
}
});
Create a separate javascript function that contains what you want to do when the button is clicked (i.e. removing the onclick attribute and adding replacement code in its own function).
Then call that function at the end of
$('button').on('click', function(){
alert('jquery');
});
So you'll be left with something like this
function buttonFunction()
{
//Do stuff here
}
$('button').on('click', function()
{
alert('jquery');
buttonFunction();
});
<button type="button">Button</button>

Categories

Resources