Okay, I am not sure if this has been asked, exactly how I did, but sorry if yes.
Basically, I have 10 items in a list.
By running this query:
public function get10items()
{
$this->query = $this->pdo->prepare("SELECT * FROM items LIMIT 10");
$this->query->execute();
while ($row = $this->query->fetch(PDO::FETCH_ASSOC))
{
echo '<li id="'.$row['id'].'">'.$row['name'].'</li><br />';
}
}
This will list 10 items from the database into '<ul>'.
This also will set an id to each item, with it's own number, like in the database.
Now, with jquery, I want the jquery to find the ID number of the clicked item.
For example our list:
Hello! [id55]
Hai! [id66]
I clicked on item 'Hello!'.
How can I find out the ID of it upon click using jquery and then use it for future use?
For example, sending ajax query, with that id, etc?
<ul class="list">
<?php echo $class->get10items(); ?>
</ul>
So basically I can use this:
$(".list").on("click", "li", function() {
$.post("ajax.php", { get : this.id }, function() {
blablabla
});
});
Is that correct?
This will trigger for every ul with li on the page. You can drill down more if the ul has an ID.
//Using event delegation since not sure when these items are being added
$("ul").on("click", "li", function() {
console.log(this.id);
});
Add a class to the li items like so :
echo '<li class = "list_item_class" id="'.$row['id'].'>'.$row['name'].'"</li><br />';
And then in jQuery :
$('.list_item_class').click(function(){
console.log(this.id);
});
This will make sure only the class items will be chosen, saving you trouble later with ambiguous selectors.
Try this:
in PHP:
public function get10items()
{
$this->query = $this->pdo->prepare("SELECT * FROM items LIMIT 10");
$this->query->execute();
echo '<ul class='someClassName' id='someUniqueId'>';
while ($row = $this->query->fetch(PDO::FETCH_ASSOC))
{
echo '<li id="'.$row['id'].'>'.$row['name'].'</li><br />';
}
echo '</ul>';
}
in jQuery:
Since you haven't posted your html code, I am delegating from document.
$(document).on('click'. '.someClassName > li', function() { // see the same class name "someClassName" is used here.
//If you give some other class name in your PHP file, change here also.
alert(this.id);//this.id is what you wanted.
});
You can also use id of the ul:
$(document).on('click'. '#someUniqueId > li', function() { // see the same id "someUniqueId" is used here, but with # prefixed.
//If you give some other id in your PHP file, change here also.
alert(this.id);//this.id is what you wanted.
});
Using jQuery to do this is really simple:
$('ul').on('click', 'li', function(e) {
var id = e.target.id;
// do your stuff with the id
});
event.target always refers to the element, that triggered the event.
So, event.target.id is the id you are looking for.
All you need is:
var clickedId;
$('li').click(function(){
clickedId = $(this).attr('id');
});
clickedId will then contain the id of the clicked element.
Or you could use tymeJV's answer which delegates the handler to the UL parent - which would have better performance for larger lists.
Related
I want to use the jQuery UI sortable function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?
The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
Example on jsFiddle.
Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1">List 1</li>
<li plid="listId2">List 1</li>
<li plid="listId3">List 1</li>
<li plid="listId4">List 1</li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>
You're in luck, I use the exact thing in my CMS
When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POST request to saveorder.php, but of course you could always post it as a regular form.
<script type="text/javascript">
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('data-article-id');
else
articleorder += "," + $(this).attr('data-article-id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('/saveorder.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
?>
<li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
<?
}
?>
</ul>
<input type='button' value='Save order' onclick='saveOrder();'/>
In saveorder.php; Keep in mind I removed all verification and checking.
<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}
?>
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/
where new order is saved in some HMTL element.
Then you submit the form with this data to some PHP script,
and iterate trough it with for loop.
Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.
I'm trying to delete ID from photos DB, but in li tags i have Categories number and i have set it to class.
Code is following:
$().ready(function() {
$(".delete").on("click",function(e) {
e.preventDefault();
var ID = encodeURI($(this).attr("id"));
var CAT = $(".photos li").attr("class");
alert(CAT);
});
});
<ul class="photos">
$sql = mysql_query("SELECT * FROM photos ORDER BY id DESC");
while($data = mysql_fetch_array($sql)){
echo "<li class='c".$data['cat_id']."'><a href='#' class='delete' id='".$data['id']."'>".$data['photo_name']."</a></li>";
}
I'm using multiple categories but when i click delete result is c1
If you are trying to delete the ID of the photo instead of the category id, why even write code for it? The following should alert you to the ID of that photo delete link you clicked on. It appears that having e.preventDefault(); at the beginning of the function prevents anything else from executing.
$(document).ready(function() {
$(".delete").click(function(event) {
var ID = encodeURI($(this).attr("id"));
var CAT = $(this).closest("li").attr("class");
alert(ID + " " + CAT);
e.preventDefault();
});
});
http://jsfiddle.net/Cq49P/5/
Cat_id is a class not an Id. Use .removeClass(). TO remove the class.
So just that I get your problem... You write the id in a class name, prefex it with c and then all elements are like: c1, c2..... and you want to get the number of c.
First of all: Use the data-attribute on the element. Example:
echo "<li class='' data-cat_id=".$data['cat_id']."'><a href='#' class='delete' id='".$data['id']."'>
(not a php expert, but your result html should look like this: <li class='' data-cat_id="1"....
This is the way I suggest you should use.
If you really really have to do it with classes
You can do it like this:
$(function($) {
var CAT = $("li").each(function() {
var CAT = this.className.split(' ');
var regex = /^c[0-9]*$/;
$.each(CAT, function(){
if(this.match(regex )){
alert(this.split('c')[1]);
}
});
});
});
[Fiddler][2].
I have a while loop which creates a list of anchor tags each with a unique class name counting from 1 to however many items there are. I would like to change a css attriubute on a specific anchor tag and class when it is clicked so lets say the background color is changed. Here is my code
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo "<a class='$i'>$title</a>
}
I would like my jquery to look something like this, it is obviously going to be more complicated than this I am just confused as where to start.
$(document).ready(function() {
$('a .1 .2 .3 .4 and so on').click(function() {
$('a ./*whichever class was clicked*/').css('background':'red');
});
});
Can you give the class a more consistent name? Like myClass_1, myClass_2, etc.
Then you could do:
$(document).ready(function() {
$('a[class^=myClass_]').click(function() { // Assign handler to elements with a
// class that starts with 'myClass_'
$(this).css('background','red'); // Change background of clicked one.
});
});
Here, a "starts with" selector is used to assign the event to all classes that start with myClass.
You could still retrieve the index number if needed.
Within the event handler, $(this) refers to the one that was clicked.
Live Example: http://jsfiddle.net/Jurv3/
Docs for "starts with" selector: http://api.jquery.com/attribute-starts-with-selector/
EDIT: I had a missing ] in the selector. Fixed now.
You can use an iterator over an array like this:
var myclasses = [".1",".2",".3"]; // generated by php
$.each(myclasses, function(index, value) {
$('a '+value).click(function() {
$(this).css('background':'red');
});
});
Note: I think you might be better off using unique ID for each item in your list of anchor tags and have them all share a single class. That's more what classes and IDs are for.
Just give them all the same class, say, myClass. Then:
$('a.myClass').click(function () {
$(this).css('background':'red');
});
This will work as long as you're having the links operate on themselves, or on their parents - as long as the relationship between link and target is the same for each. To operate on the parent, it would be $(this).parent().css(...), and to operate on the next element it would be $(this).next().css(...) and so on.
have you tried something like this?
while($row = mysql_fetch_array($results)){
$title = $row['title'];
$i++;
echo '<a class="anchor_link" id="'.$i.'">'.$title.'</a>';
}
And then for the jQuery:
$(document).ready(function() {
$('a.anchor_link').click(function() {
var thisAnchor = $(this).attr('id');
$(this).css('background':'red');
});
});
The reason for my adding the js var 'thisAnchor' is because I am assuming that you need that $i php variable as the anchor marker? if so you can just take the js var and use it however you need. if you can't use ID because the anchored content is marked by id, use a diferent attr, such as 'title' or 'alt'.
I hope this was helpful.
For example in php I have a list of clients:
foreach($clients as $client)
echo '<li id="client_'.$client->id.'">' . $client->name . '</li>';
What is the correct way to bind a click event to each list item w/o using
onclick="my_function(the_elements_id)"
right in the list item.
assuming you have a ul with id="client_list"
$("#client_list li").click(function()
{
var myid = $(this).attr("id"); // the clicked on items id
// do your thing here.
}):
And very cool "live" way of binding for all current and future matched elements. This comes in handy if you use Ajax, and have to re-bind event to let's say image that you fetch via ajax.
More info # http://docs.jquery.com/Events/live#typefn
$("p").live("click", function(){
alert( $(this).text() );
});
You can also use .bind
E.g.
$('#item').bind("click", function() { do something; });
$(document).ready(function(){
$("li).click(function(){
var id = $(this).attr("id");
your_function(id); //The function you want to run with the object's ID as a parameter.
});
});
I am doing an AJAX request with Jquery and PHP what I am doing is looping through an array and producing a table, each loop a new is created and an id is given to it, when they click the read me link the ajax and some more content is returned, on clicking read more I want the associated table row to be removed from the table is this possible, you can see my attempt so far below.
<div id="new" class="tabdiv">
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
?>
<tr id="<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
}
} else {
echo "You have no new suggestions";
}
?>
</table>
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $('a.readMore').attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function() {
$('tr').remove()
}
});
return false;
});
You can get the id of the row like this:
$(this).parent().parent().attr("id")
$(this) wraps the a element, the first parent gets the td and the next one the tr. Call this inside the click callback. Make sure that the id starts with a letter; it is not allowed to start a number. To delete it, define a variable:
var row = $(this).parent().parent();
You can then delete it at the callbacks:
row.delete();
As kgiannakakis points out you'll need a reference to the element that was clicked.
To find out what went wrong, consider the following lines of your code:
$('a.readMore').click(function(){
var url = $('a.readMore').attr('href');
...
return false;
});
What you do here is add an event handler to all a elements with a readMore class.
When the link is clicked you again select all a elements with a readMore class and retreive the href attribute from the first matched element.
What you want to do is get the attribute from the element that was clicked.
$('a.readMore').click(function(){
var url = $(this).attr('href');
...
return false;
});
The same problem occurs in the success and complete handlers of your ajax request, note that you can't use this in the success/complete handlers because it will probably point to another object so you need to store it in a var before calling the ajax function.