while ($row = mysqli_fetch_array($result)) + JAVASCRIPT error - javascript

I have a problem with some code. The proram allows me to copy from one lick one password that is sought on my BDDMysql. I have a script that allows me to copy the content of the html tag <P>, with a specific ID. All of that i got it inside of a while(mysqli_fetch_array($result)). So the problem is, when i click for copy one password, only i get the first one of the bdd copied on the clipboard.
<?php
$egest='SELECT * FROM gestion';
$result=mysqli_query($con,$egest);
while ($row = mysqli_fetch_array($result)){
//echo $row['subcat_nombre'];
?>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
<table class="estilo-ps">
<tr>
<td colspan="3" class="td-tit"><b><?php echo $row['gest_nombre'] ?></b></td>
</tr>
<tr class="tr-borders">
<th class="th-border-cent">Contrasenya</th>
</tr>
<tr class="tr-borders">
<td class="td-border-cent">
<center>
<p hidden="hidden" id="p1"><?php echo $row['gest_contra']; ?></p><br>
<p>clic per copiar la contrasenya</p>
<img src="img/key.png" class="copy" onclick="copyToClipboard('#p1')"/>
</center>
</td>
</tr>
<?php
}
?>

You can't have duplicate IDs. Use a class instead of an ID. Then use the appropriate DOM selection function to find the element with that class next to the clicked element.
Also, take the function out of the loop, it doesn't need to be redefined for each row.
<script>
function copyToClipboard(img) {
var $element = $(img).siblings(".p1");
var $temp = $("<input>");
$("body").append($temp);
$temp.val($element.text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
<?php
$egest='SELECT * FROM gestion';
$result=mysqli_query($con,$egest);
while ($row = mysqli_fetch_array($result)){
//echo $row['subcat_nombre'];
?>
<table class="estilo-ps">
<tr>
<td colspan="3" class="td-tit"><b><?php echo $row['gest_nombre'] ?></b></td>
</tr>
<tr class="tr-borders">
<th class="th-border-cent">Contrasenya</th>
</tr>
<tr class="tr-borders">
<td class="td-border-cent">
<center>
<p hidden="hidden" class="p1"><?php echo $row['gest_contra']; ?></p><br>
<p>clic per copiar la contrasenya</p>
<img src="img/key.png" class="copy" onclick="copyToClipboard(this)"/>
</center>
</td>
</tr>
</table>
<?php
}
?>

<?php
$egest='SELECT * FROM gestion';
$result=mysqli_query($con,$egest);
?>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
<table class="estilo-ps">
while ($row = mysqli_fetch_array($result)){
//echo $row['subcat_nombre'];
?>
<tr>
<td colspan="3" class="td-tit"><b><?php echo $row['gest_nombre'] ?></b></td>
</tr>
<tr class="tr-borders">
<th class="th-border-cent">Contrasenya</th>
</tr>
<tr class="tr-borders">
<td class="td-border-cent">
<center>
<p hidden="hidden" id="p1"><?php echo $row['gest_contra']; ?></p><br>
<p>clic per copiar la contrasenya</p>
<img src="img/key.png" class="copy" onclick="copyToClipboard('#p1')"/>
</center>
</td>
</tr>
<?php
}
?>
</table>
You are trying to loop the script. Script should be declared only once.
Move your while loop after <table> .

Related

Display Updated table without refreshing or reloading page

I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
    var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
 $.ajax({
      type: "post",
      url: "products.php",
      data: {id:id},
      success: function(){
        $(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
      }
    });
}
  }
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>

Is it possbile to give my "ajax-divs" URL parameters?

My app is reading information from a database and shows the information to the user using jQuery. If a user clicks on an entry, a div will popup and shows more information.
I want to open these div with a URL. Is it possible? I'm thinking about to use the entry id as a parameter?
Like this: div with entry id = 123 will open a link like this
https://url.de/index.php?param=123
// *** Funktion für Details-Overlay ***
function on(id) {
$.ajax({
url: "AJAX.php",
data: 'id=' + id + '&switch_content=details',
success: function(result) {
$("#data-table").html(result);
}
});
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
#overlay {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=12>Click on me</div>
<!-- OVERLAY -->
<div id="overlay">
<div id="ContainerBox" align="center">
<img onclick="off()" id="imgclose" src="images/auswertung-close.png">
<div id="headerSticky"></div>
<h2>Gesamte Übersicht</h2>
<hr>
<!-- Tabelle für Detailseite -->
<table data-role="table" id="data-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive" border="1" style="overflow-x: auto;">
<!-- AJAX/Informations -->
</table>
</div>
</div>
PHP/AJAX:
<?php
// Verbindung zur Datenbank
$pdo = new PDO('mysql:host=***;dbname=***', '***', '***');
$pdo ->exec("set names utf8");
if ($_GET ['switch_content']=='details'){
// SQL Befehl + ID rausnehmen
$sql_befehlDetail = "SELECT * FROM fair_contact_form WHERE id= :id";
// Ergebnisse aus dem SQL Befehl in $ergebnis ziehen
$ergebnisDetail = $pdo->prepare ($sql_befehlDetail);
$ergebnisDetail->execute(array('id'=>$_GET['id']));
$datenDetail = $ergebnisDetail->fetch();
$search = '/../../../../htdocs/..;
$replace = 'https://url.de';
$karte = str_replace($search, $replace, $datenDetail['businessCard']);
echo '<thead>
<tr>
<td class="" colspan="2"></td>
</tr>
</thead>
<tbody>
<tr>
<td data-priority="2"> ID </td>
<td> '. $datenDetail['id'] .' </td>
</tr>
<tr>
<td data-priority="2"> Handelsmesse </td>
<td> '. $datenDetail['fair'] .' </td>
</tr>
<tr>
<td data-priority="3"> Datum </td>
<td> '. $datenDetail['timestamp'] .' </td>
</tr>
<tr>
<td data-priority="4"> dateTimeOfContact: </td>
<td> '. $datenDetail['dateTimeOfContact'] .' </td>
</tr>
<tr>
<td data-priority="5"> Gesprächsdauer </td>
<td> '. $datenDetail['durationOfContact'] .' </td>
</tr>
</tbody>';
}
else if($_GET['switch_content']=='startseite') {
$sql_befehlGesamt = "SELECT * FROM fair_contact_form ORDER BY id DESC";
$ergebnisGesamt = $pdo->query($sql_befehlGesamt);
?><div data-role="header"></div>
<div role="main" class="ui-content">
<table id="table" border="1" data-filter="true" data-input="#filterTable-input" class="ui-responsive" data-role="table"
id="table-column-toggle" data-mode="columntoggle" class="ui-responsive table-stroke">
<thead>
<tr>
<th data-priority="1" id="sortieren_id">ID</th>
<th data-priority="4" id="sortieren_email" class="ui-table-cell-hidden">E-Mail</th>
<th data-priority="4" id="sortieren_gespraechsinhalt" class="ui-table-cell-hidden">Gesprächsinhalt</th> <!-- classe dient dazu, checkbox auf unchecked zu stellen -->
</tr>
</thead>
<tbody><?php
while ($datenGesamt = $ergebnisGesamt->fetchObject()) {
$dateTimeOfContact = new DateTime($datenGesamt->dateTimeOfContact);
?><tr onclick="on(<?=$datenGesamt->id?>)" style="cursor:pointer">
<td onclick="on(<?=$datenGesamt->id ?>)"><p style="color:#E3000F;"><b><?=$datenGesamt->id ?></b></p></td>
<td><?=$datenGesamt->fair ?></td>
<td><?=$dateTimeOfContact->format('d.m.Y') ?></td>
<td><?=$datenGesamt->author ?></td>
<td><?=$datenGesamt->genderOfContact ?></td>
<td><?=$datenGesamt->nameOfContact ?></td>
<td><?=$datenGesamt->surnameOfContact ?></td>
<td class="ui-table-cell-hidden"><?=$datenGesamt->companyName ?></td>
</tr><?php
} ?>
</tbody>
</table>
</div>
The information in the Ajax div should be reachable with a URL+parameter.
Yes, you can trigger the desired id details on start.
Just add next code to your js file:
// Shorthand for $( document ).ready()
$(function() {
// This code will be run when document will be loaded
var args = window.location.search.substring(1); // Get all URL arg
args = args.split('&').map(arg => arg.split('=')); // convert to array with key, value
args.forEach(function(arg) {
var key = arg[0];
var val = arg[1];
if (key === 'param') { // Check if the URL param is our param, and if yes - open popup
on(val);
}
});
});

Set value of HTML element from javascript

I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});

Execute PHP inside SCRIPT TAG

I have a listbox that displays a couple of internships under following format
id - name :
1 - Computer Science
So far, I have create the function addRow in order to update my fields from form.
If I do
alert($montext)
I can display "1 - Computer Science", but I am looking only for the value "1".
I tried :
alert(<?php substr($montext,0,2)?>);
But seems that php inside "script" isn't being executed.
Because following code changes the value in the field:
document.getElementById('ti').value=$montext;
Because I'd like also to execute php code inside the script TAG.
I'm running under Apache.
If you could help me out. Thanks
Find hereby the used code.
<html>
<head>
<script>
function addRow(title,text,description,id) {
$montext=$( "#idStage option:selected" ).text();
alert($montext);
document.getElementById('ti').value=$montext;
/*document.getElementById('te').value=text;
document.getElementById('de').value=description;
document.getElementById('id').value=id;*/
}
function setText(title,text,description,id){
document.getElementById('title').value=title;
document.getElementById('text').value=text;
document.getElementById('description').value=description;
document.getElementById('id').value=id;
}
</script>
</head>
<body>
<?php
include('../admin/connect_db.php');
?>
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<label class="notBold">Choose the internship you want to update: </label>
<select name="idStage" id="idStage" onChange="addRow()">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
while($stmt->fetch()){
?>
<option id="nostage" value="<?php echo$id;?>" onclick="setText('<?php echo $title ?>',' <?php echo $text ?> ',' <?php echo $description ?>',' <?php echo $id?>');"><?php echo $id." - ".$title;?></option>
<?php
}
$stmt->close();
}
?>
</select>
</td>
<td width="20">
<img src="./Image/exit.png" title="Close" id="closeDelete" class="closeOpt" onclick="closeOpt()" />
</td>
</tr>
</table>
<form method="post" action="modifystage.php">
<table>
<tr>
<td>
<input type = "hidden" id ="id" name="id"/>
</td>
</tr>
<tr>
<td class="label">
<label>Title </label>
<textarea id = "ti" name="ti" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $title;
?>
</textarea>
</td>
</tr>
<tr>
<td class="label">
<label>Desc</label>
<textarea id = "de" name="de" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $description;
?>
</textarea>
</td>
</tr>
<tr>
<td class="label">
<label>Text </label>
<textarea id = "te" name="te" rows = "3" cols = "75">
<?php
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT id, title,text,description FROM offre ORDER by published_date ASC')) {
$stmt->bind_result($id,$title,$text,$description);
$stmt->execute();
}
echo $text;
?>
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right"colspan="2" class="label">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
You don't need to use PHP here. Use the javascript substring function - http://www.w3schools.com/jsref/jsref_substring.asp
For example
alert(montext.substring(0, 2));
Write your <script> on bellow your PHP and try this :
<script>
function addRow(title,text,description,id) {
var montext = $( "#idStage" ).text();
alert(montext);
document.getElementById('ti').value(montext);
/*document.getElementById('te').value=text;
document.getElementById('de').value=description;
document.getElementById('id').value=id;*/
}
function setText(title,text,description,id){
document.getElementById('title').value=title;
document.getElementById('text').value=text;
document.getElementById('description').value=description;
document.getElementById('id').value=id;
}
</script>
If you want to call variable from PHP, don't forget to use echo like this :
alert("<?php echo substr($montext,0,2); ?>");

show/hide with dynamic id out of a sql database

Submenu Part
<div id="subnavigation">
<?php
$verbindung = mysql_connect("host", "user" , "pw")
or die("Verbindung zur Datenbank konnte nicht hergestellt werden");
mysql_select_db("db") or die ("Datenbank konnte nicht ausgewählt werden");
$sub_instr = mysql_query("SELECT * FROM instrument ORDER BY InstrName");
while($sub = mysql_fetch_assoc($sub_instr))
{?>
<div class="sub-item">
<p>
<button type="button" id="<? echo $sub["InstrID"] ?>" class="submenu-button"><? echo $sub["InstrName"] ?></button>
</p>
</div><?
}?>
</div>
Table Part
<div class="content-item">
<!-- Content-Item 1 !-->
<? $db_instr="SELECT * FROM instrument ORDER BY InstrName" ; $show_instr=m ysql_query($db_instr); while($row=m ysql_fetch_assoc($show_instr)) {?>
<table id="<? echo $row[" InstrID "] ?>" border="1" class="hidden">
<tr>
<th rowspan="6">
<img border="0" src="<? echo " ../SiteAdministration/ControlCenter/Instr/ ".$row["InstrImage "] ?>" alt="<? echo $row[" InstrName "] ?>" width="400" height="400">
</th>
<th colspan="2">Informationen</th>
</tr>
<tr>
<td>Name:</td>
<td>
<? echo $row[ "InstrName"] ?>
</td>
</tr>
<tr>
<td>Klanglage:</td>
<td>
<? echo $row[ "InstrKlang"] ?>
</td>
</tr>
<tr>
<td>Bauschwierigkeit:</td>
<td>
<? echo $row[ "InstrBau"] ?>
</td>
</tr>
<tr>
<td>Materialkosten:</td>
<td>
<? echo $row[ "InstrPreis"] ?>
</td>
</tr>
<tr>
<td>Infotext:</td>
<td>
<? echo $row[ "Infotext"] ?>
</td>
</tr>
</table>
<? }?>
</div>
jQuery
$(document).ready(function ()
{
$('.sub-item p button').click(function ()
{
var buttonID = $(this).attr('id');
alert('table#' + buttonID);
$('table.hidden').hide();
$('table#' + buttonID).show();
});
});
The first code example describes how I generated a list of buttons, with the ID from the sql database. So every button has it's unique ID coming from the fitting database entry.
The second code example describes a table generated from database entries, every table gets a unique ID coming from the fitting database entry.
The third code example should get the ID of the button I click, get the table with the same ID as the button, hide all tables and only show the table with the same ID as the button.
The problem is, that it won't show anyting. It just hides all tables...
Just to let you know, I'm completly new to javascript/jQuery.
ID of an element must be unique(Now you have a table and button with the same id) so use a data-* attribute in the button to store the target element id.
<button type="button" data-target="<? echo $sub["InstrID"] ?>" class="submenu-button"><? echo $sub["InstrName"] ?></button>
then in the click handler
var buttonID = $(this).data('target');

Categories