I have function:
function delMeh() {
console.log('prolazi klik');
var did = $(this).attr('data-value');
$.ajax({
url: "delTmeh.php",
type: "POST",
async: true,
data: { vrednostid:did}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#tablemeh').dataTable().fnDestroy();
drawMeh();
},
error: function(data) {
console.log(data);
}
});
}
and HTML:
<i data-value="32" onclick="delMeh();" class="fa fa-times delMeh"></i>
SO, on click I need to delete row 32 from database, but how I can get data-value of clicked element...
I try with:var did = $(this).attr('data-value'); inside delMeh() function but dont work.
How to get attr data-value of clicked element when call function like I need to do?
Why do u need the data value, when using a inline function click?
You could directly pass the value as a parameter to the function.
function delMeh(value) {
// do your stuff
}
<i onclick="delMeh(32);" class="fa fa-times delMeh"></i>
This would work good, but I seriously doubt the usage of this in a inline function call, as it could be used when a element's event is binded using jquery event listener.
Then you can use $(this).data('value')
I hope this helps.
function delMeh() {
console.log('prolazi klik');
var did = $(this).attr('data-value');
alert(did);
}
$(".delMeh.fa.fa-times").click(delMeh);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<i data-value="32" class="fa fa-times delMeh">test</i>
This uses the more standard addEventListener. AddEventListener allows for multiple events of the same type and passes the this argument to the function. It also prevents the overwriting of the inline events.
Send the element on the onclick method
onclick="delMeh(this);"
and receive the element on your function
function delMeh(element) {
// than you can get the value with
var did = $(element).attr('data-value');
// or
var did = $(element).data('value');
}
Or you could do it the jQuery way, by binding the on click handler on your html elements like this:
$(".delMeh").click(function() {
// here you could use this
var did = $(this).attr('data-value');
});
where you won't need to set the inline onclick attribute on each element.
Check this question to understand the difference between .attr vs. .data.
You really should avoid using inline event handlers with jQuery as others mention. The reason include getting new jQuery bubbling functionality and not separating the event registration code from the event handling code.
It sounds like your elements are created dynamically, which is probably why your previous attempt at using .on failed (mentioned in your comments). That also means none of the other suggestions will work as-is.
Instead use a single delegated event handler, attached to a non-changing ancestor element. document is the default if nothing else is closer/convenient. In your case the better element might be $('#tablemeh').on(..., but I would need to see a sample of your page's HTML.
A delegated event handler listens for the event (in this case click) to bubble up to the element, then it applies the jQuery selector. Then it calls your function only on the matching elements that caused the event. That means the elements only have to exist/match at event time.
Also, use data as a short-cut to fetch attributes with a data- prefix.
So instead of your existing code, just use something like this:
$(document).on('click', '.delMeh', function(){
var did = $(this).data('value');
$.ajax({
url: "delTmeh.php",
type: "POST",
async: true,
data: { vrednostid: did },
dataType: "html",
success: function(data) {
$('#tablemeh').dataTable().fnDestroy();
drawMeh();
},
error: function(data) {
console.log(data);
}
});
});
Related
I have a ul element that gets populated with li elements via AJAX.
Then I need to do something when clicking on those li elements.
The funny thing is that it works the second time I click on the li element it but not the first time.
I've read every possible related question I could find on StackOverflow but I can't find the answer to my problem.
Here is an example of the AJAX code:
$('#university').on('keyup', function(){
$.ajax({
url: ajaxUrl,
data: {
"search": searchVal,
"action": 'autoComplete',
},
type: "POST",
dataType: 'json',
success: function(data) {
$(".univers-name-list").html("");
var dataItem=[];
dataItem=data.data.items;
if(dataItem){
dataItem.forEach(function(element,key) {
$(".univers-name-list").append('<li>'+element.name+'</li>')
});
}
}
});
});
And here is the on click function (in the same file):
$('.univers-name-list').on('click', 'li', function(e){
// Code here
console.log('Helo'); // Doesn't run the first time.
});
Any idea what I'm doing wrong? Why does it only work when I click it for the second time?
Some more info:
When I checked the event target, the first time I click on any li element, the target is UL (populated with the dynamically added LI elements), but the second time is the correct LI element.
It was a custom validation rule on the input field that messed up everything.
After fixing that rule, it now works as expected.
Event listeners will not work fFor elements created dynamically via javascript.
You have to use delegate functions for these kind of elements
This code should work fine on you element created dynamically.
$(document).on('click', '.univers-name-list li', function(e){
// Code here
console.log('Helo');
});
You have to call addEventListener to the new created elements.
check this Attach event to dynamic elements in javascript
I have a page where I return users posts, these posts can be commented on the fly using some jquery code, after a new comment is posted I insert the new comment under the post along with a Delete button. The problem is the Delete button doesn't work on the newly inserted element unless I reload the page. I read that the solution is using the .on() method however I am a little confused re how to implement this.
I have one function that updates the post part with the newly inserted comment and this is the function that deletes the comment:
$(document).ready(function () {
$("button[id*='deletecmnt_']").click(function () {
var id = this.id.replace('deletecmnt_', '');
var comment_card_id = ('#comment_' + id);
var token = $(this).data('token');
$.ajax({
url: '../comment/' + id,
type: 'post',
data: {_method: 'delete', _token: token},
success: function () {
// Checks for display of comment card and removes it
if ($(comment_card_id).is(":visible")) {
$(comment_card_id).fadeOut("fast");
}
}
})
})
});
I don't understand what needs to be changed here and how.
You need to use event delegation for elements added dynamically. In your .on() method, you need to add the selector that you want the handler attached to after it's created.
$(document).ready(function(){
$("body").on("click", "button[id*='deletecmnt_']", function () {
// codes
}
});
This will listen for clicks on elements not yet created that match your selector. Here's the JQuery API doc page for more info: http://api.jquery.com/on/
I am echoing some php lines with some class id and need to be able to use them with jquery .click as the selector. Is there a way to do this?? The property is not loaded with everthing else, it is added later on by php.
play.js-
$(".link").click( function(){
/* var l = ""
$.post('input_commands/move_to.php',{l:l}, function(data) {
text=data;
elem = $("#placeholder");
//delay=100;
addTextByDelay(text,elem,delay);
}); */
alert("omg whyyyyy");
});
get_locations.php -
if($array_loc['loc_north']>0){echo "<a class='link' id='location_north'>Go north to ".$array_loc_north['loc_name']."</a> <br>";}
You need to use a delegated event because your elements are added to the DOM dynamically (or after the event handler is created).
$(document).on('click', '.link', function(){
console.log("clicked");
});
In the above, the event is delegated to the document and so all clicks will be checked against the .link selector, even if the target is an element that didn't exist when the event was delegated.
in order to bind an event to a dynamic element (one that was added after first DOM load),
replace:
$(".link").click( function(){
with:
$(document).on('click', '.link', function(){
hope that helps.
If it's added dynamically using ajax you might want to call that selector and append the .click() on the callback.
$.ajax({
url: '...',
success: function(response) {
// do stuff with response (assume that .link will be appended)
$(".link").click( function(){
//stuff when click link
}
}
});
Otherwise, you can output the links with the onclick attribute and define a custom function:
if($array_loc['loc_north']>0){echo "<a class='link' id='location_north' onclick='customFunction(this)'>Go north to ".$array_loc_north['loc_name']."</a> <br>";}
and in the JS:
function customFunction(element) {
//do stuff here after the link was clicked
//element variable passed as parameter contains the link element clicked
}
PS: If there are multiple elements it's not ok to specify constant value for "id" attribute because it should be unique.
I am using $.get to return some data:
$.get(url, function(data){
$("#searchResults").html(data);
});
When the data is returned it looks like this:
<div class="blah" cid="12344">12344</div>
I want to be able to click on this and read the CID:
$('.blah').click(function(){
$(this).attr('cid');
});
JQuery doesn't seem to handle this... am I right?
Using event delegation, you can just change
$('.blah').click(function() {
to
$('#searchResults').on('click', '.blah', function() {
and then you'll never have to remove or re-add this event handler.
You need to attach that specific event handler after inserting the HTML into the DOM.
$.get(url, function(data){
$("#searchResults").html(data);
$('.blah').unbind('click').click(function(){
$(this).attr('cid');
});
});
So I have a page that loads the data into the page through the following ajax function.
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: "POST",
url: "inc/load_data.php",
data: "p="+page+"XXXXXXXXXXX",
success: function(msg)
{
//alert(msg);
$("#container").ajaxComplete(function(event, request, settings)
{
$("#container").html(msg);
//**MODIFIED CODE
$(document).delegate('a.vote_up','click', f_vote_up);
});
}
});
}
});
//Loaded Message
$msg.='<span class="vote_buttons" id="vote_buttons'.$row['id'].'">
</span>';
The message that is loaded has some links that need to work with a another Ajax function(given below), which is apparently not working. The second function(below) is loaded before the data is loaded into the page. I suspect, may be since this function is loaded way before the data is loaded, the second function is not recognizing the click on vote_up. Is there any way to fix it??? I'm not too familiar with AJAX, I would really appreciate some help.. Thank you
$(function(){
$("a.vote_up").click(function(){
//get the id
alert("Hi");
//REST OF THE CODE
}
//***NEW FUNCTION
function f_vote_up(){
//get the id
the_id = $(this).attr('id');
//REST OF THE CODE
$("span#vote_buttons"+the_id).html("Hello, Testing Response!");
alert("End of Func!"); // <
}
When you call that second function, it's only grabbing all the a.vote_up elements that currently exist on the page. When you add more links to the page later on, they don't know to listen for the click.
You can do one of two things to fix this:
Add the click listener to each new link when you add it to the DOM. But this is a bit of work, because you'd have to change how your AJAX function builds the links, and you'd have to turn that click-listener-assigning function into something standalone that you could use at any time.
Instead of doing using the click method, use the delegate method instead:
$(document).delegate('a.vote_up', 'click', function () { ... });
More info on event delegation with jQuery.
you should bind your click event after you load the html
$.ajax
({
type: "POST",
url: "inc/load_data.php",
data: "p="+page+"XXXXXXXXXXX",
success: function(msg)
{
//alert(msg);
$("#container").ajaxComplete(function(event, request, settings)
{
$("#container").html(msg);
$("a.vote_up").click(function(){
//get the id
alert("Hi");
//REST OF THE CODE
});
});
}
});
You can use the live function to bind an event to dynamically created elements, i.e.:
$("a.vote_up").live('click', function(){
//get the id
alert("Hi");
});
http://api.jquery.com/live/
This will effectively bind this click event to all elements which match the a.vote_up selector, now and in the future.