I am trying to create a drop down menu that shows more information about each person displayed when the person is clicked on.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info').toggle();
});
});
The issue I am having is that when clicked it displays all information in each loop. So if there are 5 people and you click one name, each person populates information. The information corresponds to each person but I only want to show the info of the person clicked.
I thought this would mean that I need to somehow uniquely identify each class but cant seem to figure it out and make it work. Or maybe there is a better way to run my loop to solve the problem. Any input is appreciated. Thank you.
You can use HTML data- attributes to correlate each button to a div. Then modify the JavaScript to use the embedded data.
In the below snippet, I added data-uid attributes to both the button and the div that are populated with the uid from the database.
When the button is clicked, the data-uid is read and used to select the div with corresponding data-uid.
Another small improvement that I made was to change the type attribute on the button to button. A value of submit means that the button should be used for submit a form which is not what you are doing here.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='button' data-uid='".$row["uid"]."'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none' data-uid='".$row["uid"]."'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info[data-uid='+$(this).attr('data-uid')+']').toggle();
});
});
Wrap your .player and .player_info in a <div> and do some toggling with JQuery like so:
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='player-container'>
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
echo "</div>
}
$(document).ready(function(){
// hide all of the player_info containers
$(".player_info").hide();
$(".player-container").click(function() {
// this selects any child element of the clicked container with the
// classname .player_info and toggles it open or closed
$(this).children(".player_info").slideToggle();
});
});
You aren't specifying which player_info you want to toggle, $('div.player_info') will select all of them. A quick and dirty way to solve this would be to use select the next sibling with jQuery, relative to the button, like so:
$(document).ready(function(){
$('button.player').click(function(){
$(this).next().toggle();
});
});
Related
I have a database that contains an autoincrement id, the location and the date's trip. With this code I can show on display the result of my query.
$mysqli = new mysqli("localhost", "root", "password", "trip");
$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");
echo "<br/><h3>"."Result, I found " .$result->num_rows. " results.". "</h3><br/>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["location"]."</td><td>".$row["date"]."</td><td>".' <button type="submit" value="reserve"/>'. "</td></tr>";
}
How can I know which button the user click to reserve his trip?
$('button').on('click',function(){
alert($(this).val()); // do anything what you want
});
Sample snippet:-
$('button').on('click',function(){
alert($(this).val()); // do anything what you want
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>pahse 7, mohali</td>
<td>04/06/2019</td>
<td><button value="Click Me!">Click Me</button></td>
</tr>
Note:- instead of submit button use input type="button", as submit button used to submit form normally.
You don't need jQuery, or JavaScript at all, unless you want to submit the form with AJAX, which you haven't mentioned. You just need to fix your HTML.
<button> is not an empty element; it needs a closing tag. The text on the button goes between the tags. Give the button a name and assign the row id as its value.
$button = "<button type='submit' name='id' value='$row[id]'>Reserve</button>";
Then you can get the id of the clicked button from $_POST['id'] in the PHP script that handles the form submit.
Also, with this code
$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");
there is no way SQL injection is not a problem, regardless of what you've done on the client side. Client side validation is trivial to bypass. You need to use a prepared statement.
To get particular row information use data attribute in your button and then get that information
$mysqli = new mysqli("localhost", "root", "password", "trip");
$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");
echo "<br/><h3>"."Result, I found " .$result->num_rows. " results.". "</h3><br/>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["location"]."</td><td>".$row["date"]."</td><td><button type='button' data-bind='".$row["location"]." - ".$row["date"]."' value='reserve'/></td></tr>";
}
Use Jquery to get that information
$('button').on('click',function(){
var info=$(this).attr('data-bind');
alert(info);
});
The problem i've run into is that i have multiple buttons generated through php from data mysql data base and i do not want to manually click them all(it can go over 150). How do i make a button in HTML or PHP to click them all? or How to select the ID of each button (not manually) to include it in the General button?
I have tried onclick="document.getElementByID('').click()" atribute on the button that i want to click them all but with no succes
This is the code that i have and the issue:
<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testcases';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
//fetching data
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM test1 ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
echo "<table style=\"position:absolute; left:10px; top:80px;\" border ='1px'>";
while ($row = $result->fetch_object())
{
echo "<tbody>";
echo "<tr>";
echo "<td><textarea id=\"row->date\">". $row->date ." </textarea></td>";
echo "<td><textarea id=\"row->testcase\">". $row->testcase ."</textarea></td>";
echo "<td><textarea id=\"row->percentage\">". $row->percentage ." </textarea></td>";
echo "<td><a href='temp.php?id=" . $row->id . "'><button type=\"button\" class=\"btn\" name=\"id\" id=\"$row->id\" >COPY To Temp</button></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
}
}
// close database connection
$mysqli->close();
?>
<button type="button" style="width:200px" class="pure-button fuller-button1 blue" onclick="document.getElementByClassName('btn').click();">Copy All</button>
The expected result would be to have a table with multiple rows and button generated through php and another button to click them all, but i got stuck at the part where i need to click all the buttons.
I don't know what you really wanna do, but first of all it's a really strange thing to put a button into a link: if you want a like you can add a span child styled like a button and if you really want a button just listen to click events on it.
Another thing would be that you could use form + checkboxes so that your button can make a single action by submitting form (and this single action/HTTP query will be exploded in N actions (loop) server-side)
If you really would like to do this like you do, using ID property is not wrong but it doesn't help readability nor CSS selection, I would use data-* attributes.
So, now you want a simple answer ;)
var elements = document.getElementsByClassName("btn");
for (var i=0; i<elements.length; i++) {
elements[i].click(); // or anything you want
}
If you wanna get id properties you can do:
var elements = document.getElementsByClassName("btn");
var ids = [];
for (var i=0; i<elements.length; i++) {
ids.push(elements[i].id);
}
If you plan to use jQuery:
var ids = [];
$(".btn").each(function() {
var $button = $(this);
ids.push($button.attr("id"));
});
try this:
<button type="button" onclick="copyBtn()">Copy</button>
and using jQuery
function copyBtn(){
var id = $(this).attr("id");
console.log(id);
//do some stuff
}
I have some codes which pretty much gives me all of the Emails and Times from my database and puts it in my HTML. For every Email there is 1 Time. I pretty much want a delete button next to all of the Email+Time and when the button is pressed I want it to delete just that Email+Time. This is my code which gives me all the Emails + Times from my database:
require_once"database.php";
$result = $db->query("SELECT * FROM reserveringen");
if($result->num_rows != 0) {
$message = array();
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
$message[] = "$Email $Tijd <input type='button' value='Verwijder afspraak' name='verwijderen'/>";
}
}
<?php
if($message) {
foreach($message as $value) {
?>
<p><?= $value; ?></p>
<?php
}
}
?>
I've tried some stuff and I do have a delete button next to every Email+Time, but how do I get it that when it's pressed to just delete the Email+Time that's next to it.
http://prntscr.com/5x08bl
EDIT:
Okay, let me try to be a bit more specific.
In my database I have a table called "reserveringen". In that table there are 2 columns called "Email" and "Tijd" Everytime when I add an Email and Tijd it automatically places a button next to it in my HTML.(See printscreen above). In this printscreen you can also see that there are 3 Emails + Tijds at the moment and they all have their own button next to it. I'm not a PHP-expert but I want that if I click on 1 of those buttons it deletes the Email + Tijd that's next to it. Not just in my HTML, but also in my database. I hope this is a bit more specific.
Your possible solution is to add an anchor tag on the button and post the id of the respective content along with it.
The anchor href has the value of the page that performs the deletion query of depending upon the received content id.
<input type='button' value='Verwijder afspraak' name='verwijderen'/>
where delete.php executes your deletion query according to the id(email id) you pass along with it.
On deletion page simply get this id with $_GET['id'] and perform the deletion query on the table.
After deleting redirect the page using header('Location:yourpage.php')
Surround your button with <a> tag and in href pass path to your controller and id that u want to delete
while($rows = $result->fetch_assoc()) {
$Email = $rows["Email"];
$Tijd = $rows["Tijd"];
$message[] = "$Email $Tijd <a href='delete?id=$Tijd'><input type='button' value='Verwijder afspraak' name='verwijderen'/></a>";
}
}
and then, in scirpt under delete, get the id that you passed via $_GET['id'] and remove it from database and then redirect to your view.
i have a small website where people can submit name ideas for a project i am working on
Two things i want to implement are an upvote button (+1 to current score)
and when someone submits a name it will update the mysql array using ajax.
I am very new to Ajax and i have managed to work some code together that submits a name without leaving the current page.
This is my code for the mysql array that displays underneath the name submission form.
How can i link this upto a form submit button for refresh when a name is submitted?
<?php
$result = mysql_query("SELECT * FROM namevotes ORDER BY upvote desc")
or die(mysql_error());
echo "<center>";
echo "<table border='1' id='tablea'>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['name'];
echo "<tr><td>";
echo $row['upvote'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
?>
I am want to add a button next to each row that will increase the "upvote" by one, i know how to rig one up that will manually upvote a single entry, im not sure how to direct it to each array entry.
Method is very simple:->
1> add button in while clause using <button id="{row['id']}">like me</button>
2> create a jquery element in webpage that onclick on hitlike button trigger a event: fetch data from url by get {or post} method with data ?hitlike=id
3> before code in php tag, put if statement that if(isset($_GET['id'])) then UPDATE table SET likes=likes+1 WHERE id=$_GET['id']
4> rest code will be the same to show data
//I haven't tried this but I think it should work
what i have is a list of posts on a page then each post has an icon to add to favorites (also has a watch button but it works the exact same to this) when clicked it calls the page with the script to add this post to ur favorites list in the database. (before using ajax i used a php redirect which returned to the previous page) when the page gets refreshed the database gets checked for what posts you have on your favorites list and will show the appropriate image depending on if its on ur favorites list or not.
When i click the link it appears to do what it should (go to the page and runs the update query to the database) but rather than refresh the div it just clears it. when i press f5 to refresh the page the image now displays the ticked image as it should so the query to the database is made when i click and the div gets kind of refreshed but it requires a proper refresh for it to display.
echo '<div id = "favwatchbox'.$ID.'">';
if($_SESSION['Valid'] == "True" ){
$userid = $_SESSION['ID'];
$check= "SELECT * from UserFavoritePost WHERE UserID='$userid' AND PostID='$ID'";
$resultcheck = $db->query($check);
$num_resultcheck = $resultcheck->num_rows;
$checklater= "SELECT * from UserViewLaterPost WHERE UserID='$userid' AND PostID='$ID'";
$resultchecklater = $db->query($checklater);
$num_resultchecklater = $resultchecklater->num_rows;
$prelogin = $_SERVER["REQUEST_URI"];
if($num_resultcheck >= 1)
{
echo "<a id = 'favdel".$ID."' href='#'><img id='Fav' title='Favorited' src='images/site-design/Favoritecheck.png'></a>";
?>
<script>
$(function() {
$("#favdel<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("sql-scripts/deletefavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
else
{
echo "<a id = 'favadd".$ID."' href='#'><img id='Fav' title='Mark as Favorite' src='images/site-design/Favorite.png'></a>";
?>
<script>
$(function() {
$("#favadd<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("phpincludes/markasfavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
}
the page for deleting from favourites
<?php
include '../phpincludes/dbconnection.php';
$userid = $_GET['user'];
$postid = $_GET['post'];
$query = "DELETE FROM UserFavoritePost WHERE UserID='$userid' And PostId='$postid'";
$result = $db->query($query);
$presubmit = $_GET['pre'];
if($presubmit == "/myaccount.php")
{
header("location:".$presubmit."");
}
?>
i have included an img src in the delete from favorites php file and now when you click it does the update and updates the image but when i click the link again to re add to my favorites it just brings me to the top of the page. if i refresh and click it will then run the add script but it still isnt refreshing the div properly