jQuery select every time first element - javascript

HTML:
<div class="vote" id="<?php echo $id; ?>">
jQuery:
$('.vote').on('click', function() {
var div = $(".vote").attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(".vote").attr('id')
},
success: function(data) {
alert(div);
}
});
});
this works, but div var it's always first element - and runs twice (two divs with vote class).
I use AJAX for displaying results (divs with vote class) also.
Why is this happening and how can I fix?

You need to use this, which refers to element which invoked the element.
var div = $(this).attr('id'); //this.id;
When you are using $(".vote").attr('id') it will always return you id of first element.
As you are using id to store custom data. I would recommend you to use data-* prefixed custom attribute which can be fetched by using .data()
<div class="vote" data-id="<?php echo $id; ?>">
Then you can use
var id = $(this).data('id');

You need to use current elements clicked context this:
var div = this.id;

Replace your $('.vote') to $(this) like this below:
$('.vote').on('click', function() {
var div = $(this).attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(this).attr('id')
},
success: function(data) {
alert(div);
}
});
});

Use this.id instead of $('.vote').attr('id'), because javascript will get the first id he founds if you use $('.vote').attr('id')

Related

row().data to retrieve a specific column row using datatables.net plug-in

EDIT: Deleted my YouTube Video, here is simple solution:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
"Working Code":
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
$.ajax({
url: 'index.php',
datatype: "json",
data: { edit_id : edit_id },
async: false,
success: function(result) {
//alert(edit_id);
$("#edit_id").val(edit_id);
} //success func
}); //ajax
}); //end ready
</script>
What I tried
I tried many things as in the youTube video. I could not get the original example to work on the link.
Should I use Jquery like this??
var last_name = $('#example').DataTable().row( last_name ).data();
Or php like this?
$('#editLastName').val( <?php echo $row['first_name']; ?> );
Or something within the ajax file?
What you could try is to get the parent tr element, although I'm not sure if that's the best approach.
Simplified:
$(document).on('click', '.edit_btn', function() {
var rowData = $('#example').DataTable().row($(this).parents('tr')).data();
});
Basically you get the parent tr from the button element you click on and get the data from that row.
What I also noticed, your data-id from the button seems messed up. It looks like this: data-id='s-"0"'. I'm not sure how you generate this, but in case you fix that and it looks like data-id="0" you can select rows with $('#example').DataTable().row($(this).data('id')).data();.
As you can see, there are quite a few possibilities here.

execute command to new loaded content from ajax jquery

I got some problem with jquery.
<select class='my-select' id='exist_select'></select>
<div id='target'></div>
<script>
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select = '<select class="my-select" id="select'+data[key]+'"></select>';
}
$('div#target').html(select);
$('.my-select').append($('<option>', {
value: 100,
text: 'Added option',
}))
})
})
</script>
The selects was successfully loaded. As you see, I tried to make HTML selects. Then append spesific option manually for each select.
Unlucky, It doesn't work. But it works on #exist_select.
I have no idea. Please help me.
First wrap your code in a document ready statement, second your loop only gets the first element, you need to use concatenation to append the rest,3th you can append the option directly in the select:
$(function(){
$.ajax({
type : 'GET',
url : "<?php echo site_url().'rekap/get_akun?id_subkom=' ?>"+id_subkom,
dataType : 'json',
success: function(data){
var select = '';
for (var key in data){
select += '<select class="my-select" id="select'+data[key]+'"><option value="100">Added option</option></select>';
}
$('div#target').html(select);
})
})
})
Event listeners can only be attached to elements that are in the DOM, not elements that don't exist at the time.
For dynamically created elements, you need to use the .on function:
$('body').on('change', '.my-select', function(){
alert('here');
});

Jquery removing issue divs still remains

Yesterday I coded a Commentbox in PHP, HTML and ajax. The ajax part gives me the opportunity to delete a comment without refreshing the page. The way I do this, is that I give each and every comment (div) a unique id via the database. So let us for example say that in my mysql database this is how a comment looks like:
Username: blabla<br>
Comment: haha this is so funny<br>
id: 52
This will be printed out in the html page likes this for example:
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment">Delete the comment here!</div>
</div>
AND THEN!
Comes the ajax part which is coded something like this:
$(document).ready(function(){
$(".deleteComment").click(function(){
//Getting the id of comment
id = $(".deleteComment").attr("id");
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
});
This works fine when deleting the first comment. But it WONT LET ME DELETE OTHER COMMENTS UNLESS I REFRESH THE PAGE >.<. The first comment can be perfectly deleted without refreshing the page, but when I want to delete other comments I have to refresh the page multiple times.
How do I solve this?
The code in your document ready event would work properly only for the first click. In order to get this work, you must have an on click event registered within the tag.
Example :
<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>
function DeleteMe(id)
{
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
}
If the on click on a div does not work, you can use an anchor tag (Delete here) instead.
.deleteComment is child of <div class="commentStyle".., so you can select it with parent() selector:
var id = $(this).parent().attr("id");
Or more specifically:
var id = $(this).parent('.commentStyle').attr("id");
Looks like you need to get the id from the parent element first and then target the child, the element you clicked, to hide the comment from it after the ajax request returns success:
$(".deleteComment").click(function(){
var id = $(this).parent().attr("id");
var child = $(this);
$.ajax({
type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
child.hide();
// or if you want to delete the entire element with the id of X
// child.parent().hide();
}
});
});
There are few changes which need to be done in your code.
First of all add ID tag to the inner div.
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here! </div>
</div>
Secondly use this
id = $(this).attr("id");
instead of...
id = $(".deleteComment").attr("id");
Thirdly change the ajax call like this:
$.ajax({
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id
}).done(function(){
$("#" + id).hide();
});
Hope this works for you, if not just reply me.

Creating a link to pass a PHP venerable to jQuery

I can not seam to be able to figure out why the code below is not adding the id to the jQuery script, I do know that the $value['expid'] has the value of 13 in it and it is my understanding that echoing this PHP code will make jQuery see the number that is in the venerable.
The leak that creates the data-id value grabbed by the jQuery script
<a href='#' class='open-editexpenses' data-target='#editexpenses' data-id='<?= htmlspecialchars($value['expid'], ENT_QUOTES, 'UTF-8') ?>'>Edit</a>
The jQuery script
$(document).on('click', '.open-editexpenses', function() {
var id = $(this).data('data-id');
alert(id);
$.ajax({
type: "POST",
url: "expmodal.php",
data: {id: id},
success: function(html) {
$('body').append(html);
$('#editexpenses').modal('show');
}
});
});
Use
$(this).data('id')
Or
$(this).attr('data-id');
(The first is usually preferable)

jQuery selectors after dynamic reload, and $(this)

I need some help. I load a list of entries in a div every 5 seconds. Each entry is a div and has a unique ID. Like this:
<div class="entry">
<div class="textbox">
<p class="entry-text">
<?php echo $text;?>
</p>
</div>
<div class="infobox">
<p class="date"><a #<?php echo $id;?> id="<?php echo $id;?>" href="gen_details.php?id=<?php echo $id;?>"><?php echo $t;?></a> </p>
<p class="ip"><?php echo $ip;?></p>
</div>
These, as I said are loaded each 5 seconds. I'm adding a details page for every entry, with this:
$('.date a').click(function () {
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
return false;
});
This works perfectly fine, until it reloads. It seems to lose the handle for the a href and instead of doing the procedure it goes to gen_details.php
I have tried to use .on() but I don't know how would I get the ID of the entry using .on(), as I cant use $(this) (afaik).
I hope I explained my problem at least half-well. English is not my first language so it wasn't that easy.
Thanks in advance.
Try this selector
$('div').on('click', '.date a', function () {
This will delegate the event to its parent div. So it should work for dynamically created elements as well.
Live click event bind event handler to element even after you reload some element. Default click event bind to element when a page load once you reload that element then it also delete event handler of that element.
works on till jquery 1.7 version.
$('.date a').live('click',(function (e) {
e.preventDefault()
var dataString = 'id=' + $(this).attr("id");
//alert(dataString);
$.ajax({
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
$("#content").hide().fadeOut('fast');
$("#content").html(data).show('fast');
refresh = 0;
},
});
});
//when jQuery > 1.7 then used this method
$('body').on('click' '.date a',function () {
//call
});

Categories

Resources