For starters, here is my php:
$id2 = mysql_real_escape_string($id2);
$getdata8 = mysql_query("SELECT * FROM musicbook WHERE identify='$identify' ORDER BY id DESC LIMIT 20");
$numrowsgetdata = mysql_num_rows($getdata8);
if ((mysql_num_rows($getdata8))<1)
{
echo "<i>Be the first to say something?</i><p/>";
}
while ($row8 = mysql_fetch_assoc($getdata8))
{
$id8 = $row8['id'];
$name8 = $row8['name'];
$message8 = $row8['message'];
$message10 = nl2br($message8);
$date8 = $row8['date'];
if ($name8==$username)
{
echo "
<div class='messagediv' style='background:#1A1A1A;'><div style='padding:5px;'>$message10<br/>
<div style='margin-top:4px; font-size:.8em; float:left;'><div style='float:left;'><a href='http://www.pearlsquirrel.com/$name8' style='color:white;'>$name8</a><font style='color:#D6D6D6'> on $date8</font></div>
<input type='hidden' id='wpm2' value='$id8'><input type='button' id='deletelistenchat' class='deletelistenchat' style='display:none;' onclick='LinkOnClick2($id8); loadlistenchat();' value='(delete?)' /></div></div></div>
";
}
else
{
echo "
<div class='messagediv'><div style='padding:5px;'>$message10<br/>
<div style='margin-top:4px; font-size:.8em; float:left;'><div style='float:left;'><a href='http://www.pearlsquirrel.com/$name8' style='color:white;'>$name8</a><font style='color:#D6D6D6'> on $date8</font></div>
</div></div></div>";
}
}
if($numrowsgetdata >= 20)
{
echo "<div id='loadingcomments'><img src='loading.gif' style='height:30px; width:30px;'></div>";
}
?>
Here is my jquery:
$('.messagediv').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
document.getElementById('deletelistenchat').style.display='block';
} else {
document.getElementById('deletelistenchat').style.display='none';
}
});
Now what I want to happen is that for each .messagediv div when you hover over it, it shows the delete button, #deletelistenchat. However, it only works for the last row of each mysql query and I want the hover effect to work on each one as a user hover over it. For example, if I hover over the first post by a user, the hover effect activates on the last post retrieved by the mysql query. I have been trying to figure this out for some time now, and am lost as anything. Help would be appreciated.
ID's are unique. You are using the same ID over and over, because of this, the DOM is only finding the last element with that ID -- that's the intended effect, it's a result of how you wrote your php.
<input type='button' id='deletelistenchat'
Remove the ID from this button. You already have the class here.
let's change your hover event.
$(function(){
$('.messagediv').on('mouseover', function() {
$(this).find('.deletelistenchat').css('display', 'block');
}).on('mouseout', function(){
$(this).find('.deletelistenchat').css('display', 'none');
});
});
*Edit*
DOM Behavior wasn't functioning as expected because I didn't clearly look at your markup, that's my fault. Made it jQuery 1.7 worthy, and separated your mouseover and mouseout statements to be able to clearly see them.
The working Fiddle -> http://jsfiddle.net/6MpX9/
Related
So I've got a data table that is updated with two different sets of buttons. The jquery is thus;
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id});
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id});
}
});
It literally just grabs the id of the button clicked and passes what was clicked to the load to refresh the data table.
(On an unrelated note, I'm new to jquery but I've got my load pointing at itself. So index.php is the page the code is on and I've just got it pointing at a div lower down to update that. It works - and shouldn't get stuck on an infinite loop because it's only triggered on clicks - but I feel like it's wrong and bad coding. Can someone confirm or deny this?)
The issue I have is that when you click the ASC or DESC buttons, it doesn't pull the week through because that's on a different button. I think it's because of the PHP at the top of the page that pulls it;
$this_week = $_POST['this_week'] ?? '202118';
$up_down = $_POST['up_down_type'] ?? 'ASC';
$sort = $_POST['sort_type'] ?? 'nt_login';
$breakdown = get_adv_breakdown($this_week, $sort, $up_down);
And it's because of the '?? '202118' bit, which is defaulting to 202118 as the week instead of the currently selected week.
How do I get it to update the ASC values and keep the currently selected week? I feel like I need to somehow store the week somewhere else, but this is hitting the limit of my jquery knowledge.
Here's a visual of the final page, showing the two different sets of buttons;
https://i.stack.imgur.com/UU8Kd.png
I've added the html that generates the buttons;
<td align="center">Advisor<button name="ASC" id="nt_login"><i class="arrow up"></i></button><button name="DESC" id="nt_login"><i class="arrow down"></button></td>
etc
etc
And a little loop that adds the last 12 weeks;
<div id="week-buttons">
<p align="center"><?php foreach($no_weeks as $week) { ?>
<button name="sky_week" class="sky-primary-button w-button" id='<?php echo h($week['Week']); ?>' onclick="this.blur();">
<?php echo h($week['Week']); ?>
</button>
<?php } ?></p>
</div>
It looks like you are reloading your page whenever you do a sort. In order to preserve the value of $this_week you will need to pass that as a $_POST value to your page when you fire .load()
It should be as simple as doing something like this:
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id}); // this seems to be an error?
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id, this_week: $this_week});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id, this_week: $this_week});
}
});
$last_itteration = false;
while($row = mysqli_fetch_array($result)){
if ($row['egenskaps_navn'] == $last_itteration) {
} else {
echo "<h3>".$row['egenskaps_navn']."</h3>";
}
echo "<span id='verdi_" .$row['verdi_id']."'>".$row['verdi_tekst']."</span><br />";
$last_itteration = $row['egenskaps_navn'];
}
$(document).ready(function(){
$('h3').click(function(){
$('span').toggle();
});
I have collected data from a database. The idea is that I want to toggle values to show from a list of properties (marked h3). The while loop only prints a property if it already hasnt been printed and the connected values. They are currently hidden in the CSS with "span {display: none;}". Now the toggle will only work for all the values and not the connected ones. Is there a similar way to do it in jquery or javascript as i have done it in the PHP code? To select only one property (h3) for toggling since i don't want to toggel them all at once.
Use nextUntil('h3') to toggle everything between the clicked h3 and the next h3:
$('h3').on('click', function() {
$(this).nextUntil('h3').toggle();
});
Here's a fiddle
This triggers the closest span to the h3 clicked
$(document).ready(function(){
$('h3').click(function(){
$(this).next('span').toggle();
});
});
or as billyonecan mentioned:
$(this).nextUntil('h3','span').toggle();
the second argument makes the function select only the spans
Find the next span of the current h3 on click event on h3 and apply the toggle to it. Try with -
$('h3').click(function(){
$(this).next('span').toggle();
});
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.
I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/
I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>