When using a <p> my script works. When I replace this with a table, it doesn't want to follow the rules of my script. The table is supposed to drop down under a button when clicked.
Im using php to get information from the database, but this shouldnt interfere as the data shows correctly in the table. I have tried to put the table in the div. I have tried different kind of style.height/style.display in the javascript.
this works properly
<h1 type="button" class="stelling">Where the sun?
</h1>
</div>
<div id="p1" class="data">
Here comes the sun!
</div>
but when I try to put a table in
<div class="stellingen";>
<div type="button" id="btn1" class="stelling-wrapper">
<img src="images/button.svg" alt="Show more..." class="btn" id="bton">
<p type="button" class="stelling">
</div>
<?php
$sql2="SELECT * FROM stellingen WHERE stelling_ID=1;";
$records2 = mysqli_query($con, $sql2);
$recordscheck2 = mysqli_num_rows($records2);
if ($recordscheck2 > 0){
while ($stellingen = mysqli_fetch_assoc($records2)){
echo "<p>".#$stellingen['Stelling']."</p>";
}
}
?>
Here is where I use the same id, just like the example that worked, i also tried with table id=p1
<div id="p1">
<table id="tabel" class="data">
<tr>
<th>Title</th>
<th>Source</th>
<th>Weight</th>
<th>Date</th>
</tr>
<?php
$sql1="SELECT * FROM stelling WHERE stelling_iD=1;";
$records1 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records1);
if ($recordscheck > 0){
while ($stelling = mysqli_fetch_assoc($records1)){
echo "<tr>";
echo "<td>".#$stelling['Title']."</td>";
echo "<td>".#$stelling['Source']."</td>";
echo "<td>".#$stelling['Wheight']."</td>";
echo "<td>".#$stelling['Date']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
</div>
</div>
The javascript
<script>
window.onload = function() {
var a = false;
document.getElementById('btn1').onclick = function (){
if(a== false){
document.getElementById('p1').style.height = "auto";
a =true;
}else{
document.getElementById('p1').style.height = "0px";
a =false;
}
}
}
</script>
I expect a div wit my table to drop down when clicked on the button
Related
I have a select div, with some options. When I select option 1, it shows me two buttons and for each button, when I click, it return me two tables (button one return me table one and button two return me table two). This is working ok, but I'm facing some problems to display the result after the php validate the inputed data.
What I have is this:
My php script:
<div id="main">
<?php
$area = $_POST['area'];
$url = "http://worldtimeapi.org/api/timezone/$area";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result, true);
?>
<div class="select">
<select onchange="displayDiv('hide-buttons', this)">
<option value="0">Select an action</option>
<option value="1">Create</option>
<option value="2">Consult</option>
</select>
</div>
<div id="hide-buttons" style="display:none">
<div class="col-md-8">
<button id="button1" onclick="showTable1()">Time</button>
<button id="button2" onclick="showTable2()">Area</button>
</div>
</div>
<div id="table1" style="display:none">
<form method="POST">
<label for="area">Insert area:</label>
<input type="text" id="area" name="area">
<input class="button3" type="submit">
</form>
<?php
if (empty($area)) {
echo "<p class='empty-message'>" . "Insert an area" . "</p>";
?>
<tr></tr>
<td></td>
<?php } else if (preg_match('/error/',$result)){
echo "<p class='invalid-message'>" . "Invalid area" . "</p>";
?>
<tr></tr>
<td></td>
<?php } else {
echo "<p class='valid-message'>" . "Valid area" . "</p>";
?>
<table id="area-value">
<tr>
<th>Area</th>
</tr>
<tr>
<td><?php echo $data["timezone"];}?></td>
</tr>
</table>
</div>
<div id="table2" style="display:none">
<form method="POST">
<label for="area">Insert time:</label>
<input type="text" id="area" name="area">
<input class="button3" type="submit">
</form>
<?php
if (empty($area)) {
echo "<p class='empty-message'>" . "Insert an area" . "</p>";
?>
<tr></tr>
<td></td>
<?php } else if (preg_match('/error/',$result)){
echo "<p class='invalid-message'>" . "Invalid area" . "</p>";
?>
<tr></tr>
<td></td>
<?php } else {
echo "<p class='valid-message'>" . "Valid area" . "</p>";
?>
<table id="time-value">
<tr>
<th>Time</th>
</tr>
<tr>
<td><?php echo $data["datetime"];}?></td>
</tr>
</table>
</div>
</div>
And JavaScript:
function displayDiv(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 2 ? 'block' : 'none';
}
function showTable1() {
document.getElementById("table2").style.display = "block";
document.getElementById("table1").style.display = "none";
}
function showTable2() {
document.getElementById("table2").style.display = "none";
document.getElementById("table1").style.display = "block";
}
As you can test, my problem is when I submit the input, it will make the request and retrieve the response, but I have to select option and click on the button again to see the response. I'm very new to it, I tried to made changes but it keeps getting worst. How can I do it?
You could make a function on load to check the response div and see if it has changes, and then you can directly show the div with the results, or trigger the button click, how to do that?
I first assume you have jQuery installed because then it's easier to just create an event rather than doing it in plain javascript (it's also helpful to use jQuery if you are starting), so if you have jQuery you could do this:
function displayDiv(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 2 ? 'block' : 'none';
}
function showTable1() {
document.getElementById("table2").style.display = "block";
document.getElementById("table1").style.display = "none";
}
function showTable2() {
document.getElementById("table2").style.display = "none";
document.getElementById("table1").style.display = "block";
}
$(document).ready(function(){
checkForResponse(); // calls this function when loading the screen
});
function checkForResponse(){
//Checks if table1 child p element has valid-message then shows the table1
if($('#table1 p').hasClass('valid-message')){
showTable1();
}
//Checks if table2 child p element has valid-message then shows the table2
if($('#table2 p').hasClass('valid-message')){
showTable2();
}
}
This could be later refactored but I think is an idea to get you going, good luck.
I have a html/php code as shown below. The below html/php code is working in a way that on adding rows, we can select date from every row and can save it as well.
Two things need to be done.
On clicking Delete button, it should remove the value from the JSON array because everything is pulled from the JSON after saving the form.
Also, on clicking Delete button it should delete the complete row from the DOM.
you should give each added row an id corresponding to its rank:
row.id=i.toString();
then use the following code to remove the row:
var row = document.getElementById(rowrankid);
row.parentNode.removeChild(row);
I have prepared a code sample for you using your example that does exactly what you say.
It is using a javascript fetch post request to post to the script you have provided to remove the dom elements and update the json file.
I have changed some of your paths slightly so you will need to change those back (add in the ../feeds/ parent directory)
Once the user has pressed the button the page will reload, showing the updated interface that is loaded from the json file.
There are some improvements that could be made, for example the javascript is not checking to make sure the request was successful before reloading, but as the input is date select it should be ok.
<?php
if(file_exists('./ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('./ptp-ess_landing_house.json'));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST['requestType']) && in_array($_POST['requestType'], ['remove'])) {
switch ($_POST['requestType']) {
case 'remove' :
//Unset the values
unset($data->row_delete[$_POST['data'] -1]);
unset($data->house_sitting_date[$_POST['data'] -1]);
//We are reindexing the arrays as we have deleted some rows, note that we are using +1 array indexes
$data->row_delete = array_values($data->row_delete);
$data->house_sitting_date = array_values($data->house_sitting_date);
foreach($data->row_delete as $key=>$value) {
$data->row_delete[$key] = strval($key+1);
}
//Write the file back
$fp = fopen('./ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
header("HTTP/1.1 200 OK");
echo 'ok';
die;
break;
default:
}
}
}
?>
<script>
function rowDelete(row) {
//Make a request to your entry file (index.php here) to do the removal
fetch('/index.php', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({requestType: 'remove', data: row})
}).then(function(response) {
location.reload();
return response;
});
}
</script>
<?php if($data) { ?>
<form method="post">
<div id="rows" style="display:flex; justify-content: center;"><!-- Big div START -->
<!-- Remove Button START -->
<div class="rows-delete">
<h4 style="text-align:center;">Delete Rows</h4>
<?php if (empty($data->row_delete)) { ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button type="button" id="delete" onclick="rowDelete()">Remove</button>
<input type="hidden" name="row_delete[]" value="1" />
</div>
<?php } else { ?>
<?php foreach ($data->row_delete as $row_delete){ ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button id="delete" type="button" onclick="rowDelete(<?php echo $row_delete;?>)">Remove</button>
<input type="hidden" name="row_delete[]" value="<?php echo $row_delete;?>" />
</div>
<?php }} ?>
</div>
<!-- Remove Button END -->
<!-- Sitting Date START -->
<div class="sitting-days">
<h4 style="text-align:center;">Select Date</h4>
<?php if (empty($data->house_sitting_date)) { ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="">
</div>
<?php } else { ?>
<?php foreach ($data->house_sitting_date as $date){ ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="<?php if($date) {echo $date;}?>">
</div>
<!-- Select Date END -->
<?php }} ?>
</div>
<!-- Sitting Date END -->
</div><!-- Big div END -->
</form>
<?php } else {
echo 'Cannot read JSON settings file';
}
?>
If your json is known at the front-end (which I think you are implying, since your rowDelete is a JS-function), you can pass this with the call to rowDelete. Then you can traverse the DOM to get to value the corresponding sibling input-field (perhaps something like this.parentNode.childNodes[1]).
Once you have that value, you can easily remove it from the corrsponding array in your json:
let d = '2020-01-30'
let idx = arr.indexOf(d)
let newdates = ([...arr.slice(0,idx), ...arr.slice(idx+1)])
data.house_sitting_date = newdates
(with some additional index bounds checking, of course).
After that, you can perform a similar DOM traversal to remove the corresponding element from the DOM.
Flash, unfortunately, the desing of the code itself is not much professional... there are separate loops for rows (in php), which instead should be only 1 loop, like (with example simple Javascript binding on click):
<?php
for ($i=0; $i<count($data["house_sitting_date"]); $i++)
{
echo '<div class="remove"><a id="'.$data["row_delete"][$i].'" onclick="deleteRow(this);">Remove</a></div>';
echo '<div class="date">....</div>';
...
}
?>
<script> function deleteRow(el) { el.remove(); } </script>
also, lots of embedded style="".. codes, instead you might use 1 style file.
This is how I did in past, and it works perfectly
Prerequisite for this answer to work is each button and input field should be in DIV with unique id and there should be container for all these div in my case its .
On Add button(if you have one) you need clone node, and paste it under or above the element where it was clicked,
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Then every time you add a new row or delete a row you need to append ids on these row, to do this you would a common class for all these rows in my case I used, rows
function changeids()
{
let rows =document.getElementsByClassName('rows');
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
Then when you remove you need to remove node and call changeids again
function removerow(rownumber){
document.getElementById('row'+rownumber).remove();
changeids();
}
This would give you whole working idea of add and delete rows, whole code below please ignore my messy code, just did it to give you and idea
<p>
<div id="row1" class="rows">
<button class="add" onclick="addrow(1)">add</button>
<button class="delete" onclick="removerow(1)"> remove </button>
<input type="text">
</div>
</p>
<script>
function addrow(rownumber)
{
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
changeids();
}
function removerow(rownumber)
{
document.getElementById('row'+rownumber).remove();
changeids();
}
function changeids()
{
let rows =document.getElementsByClassName('rows')
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
</script>
To delete row from dom, you have to specify unique id for main element of row and you can use [ElementObject].remove() method to delete, So everything inside that will be removed.
Also You should simplify and change JSON data, so that it will delete from json also using ajax with using single id(key) as parameter.
Here is the working code:
<?php
if (!empty($_GET)) {
if (!empty($_GET['action']) && $_GET['action'] == 'delete') {
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
if (!empty($_GET['row_number'])) {
unset($data[$_GET['row_number']]);
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
echo 1;
exit;
}
}
echo 0;
exit;
}
}
if (!empty($_POST)) {
$output = array();
if (!empty($_POST['row_item'])) {
$output = $_POST['row_item'];
}
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
$data = array();
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
}
?><form method="post">
<!-- Add New Row Button START -->
<div class="plus-minus-button" style="text-align:center;">
<button type="button" id="addRow" onclick="rowAdd()">+</button>
</div>
<!-- Add New Row Button END -->
<div id="maindiv">
<div style="display:flex; justify-content: center;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<h4 style="text-align:center;">Delete Rows</h4>
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
</div>
</div>
<div class="choose-options" style="text-align:center;">
<div class="yes-no-option" style="display:inline-grid;">
<h4 style="text-align:center;">Yes/No</h4>
</div>
</div>
</div>
<!-- Big div START --><?php
$totalrow = 0;
foreach ($data AS $key => $row) {
?><div id="row-<?php echo $key; ?>" style="display:flex; justify-content: center; margin-top:20px;"><?php
?><div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="<?php echo $key; ?>">Remove</button>
<input type="hidden" name="row_item[<?php echo $key; ?>][row_delete]" value="<?php echo $row['row_delete'];?>" />
</div>
</div>
<!-- Remove Button END -->
<!-- This is what I have tried to add a button (END) -->
<!-- Sitting Date START -->
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[<?php echo $key; ?>][house_sitting_date]" value="<?php echo $row['house_sitting_date']; ?>">
</div>
</div>
<!-- Sitting Date END -->
<!-- YES/NO START --><?php
?><div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[<?php echo $key; ?>][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "nada" ) echo "selected";?>>Please choose an option</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "yes" ) echo "selected";?>>Yes</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "no" ) echo "selected";?>>No</option>
</select>
</div>
</div>
<!-- YES/NO END -->
</div><?php
if ($key > $totalrow) $totalrow = $key;
else $totalrow++;
}
?>
<input type="hidden" name="totalrow" id="totalrow" value="<?php echo $totalrow; ?>">
</div>
<!-- Big div END -->
<hr />
<div style="text-align:center;">
<input type="submit" value="submit" />
</div>
</form>
<script>
function delete_row(row_number) {
var data = '<?php echo json_encode($data) ?>';
data = JSON.parse(data);
if (typeof(data[row_number]) != undefined) {
var request = new XMLHttpRequest();
request.open("GET", "index.php?action=delete&row_number=" + row_number);
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
request.send();
}
else {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
function rowAdd(event) {
var totalrow = document.getElementById("totalrow").value;
totalrow = parseInt(totalrow) + 1;
document.getElementById("maindiv").insertAdjacentHTML('beforeend', newRow(totalrow));
document.getElementById("totalrow").value = totalrow;
}
function newRow(row_number) {
return `<div id="row-` + row_number + `" class="sitting-days" style="display:flex; justify-content:center; margin-top:20px;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="` + row_number + `">Remove</button>
<input type="hidden" name="row_item[` + row_number + `][row_delete]" value="` + row_number + `" />
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[` + row_number + `][house_sitting_date]" value="">
</div>
</div>
<div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[` + row_number + `][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="nada">Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>`;
}
</script>
I am trying to run a form that stores an Id in a hidden input tag so that I can retrieve it in the next page using php. For some reason I can't retrieve the value using the php file. Echoing orderId.value and order number are working fine.
main_page.php
<script>
function EditValues(orderNumber) {
var orderId = document.getElementById("orderId");
orderId.value = orderNumber;
document.forms["form1"].submit();
}
</script>
<body>
<form action="edit-form.php" id="form1">
<div class="container">
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId"/>
<?php
require("config.php");
$con = new mysqli(DB_Host, DB_User, DB_Password, DB_Name);
if ($con->connect_error) {
die("Connection failed");
}
echo '<table id="tblOrders" name ="OrderTable" style="width: 100%">
<tr>
<th>Sno</th>
<th>Order Number</th>
</tr>';
$displayTableDataQuery = "SELECT id, orderNumber, customerName, deliveryDate FROM orderTable";
if ($tableData = $con-> query($displayTableDataQuery)) {
while($row = $tableData-> fetch_assoc()) {
$id = $row['id'];
$orderNumber = $row["orderNumber"];
echo '<tr >
<td>'.$id.'</td>
<td id = "orderNumber">'.$orderNumber.'</td>
<td><input type = "button" id ="editButton'.$id.'" value = "Edit" onclick = "EditValues('.$orderNumber.');"/> </td>
<td><input type = "button" id = "printInvoice'.$id.'" value="Print" onclick = "PrintInvoice('.$orderNumber.');" /> </td>
</tr>';
}
} else {
echo $con->error;
}
$tableData->free();
?>
</div>
</form>
</body>
In edit-form.php
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
There is nothing echoed for $xyzabc
I would prefer if there was some way to do this without jQuery as I'm kind of new to this and haven't really gotten a hang of how everything works together as of now.
You can store value directly to the hidden input field.
<!--use the hidden input variable to save the order number clicked -->
<input id="orderId" type="hidden" name="orderId" value="<?=$variable_name;?> />
So that when you submit the form
<?php
$xyzabc = $_POST['orderId'];
echo $xyzabc;
?>
will fetch the data.
Or you can pass the hidden value in url. For example
<a href="localhost:8000/edit-form.php?orderId="<?=$variable_name;?>
Then in you form-edit.php
<?php
$xyzabc = $_GET['orderId'];
echo $xyzabc;
?>
On my database i have a table product_category, with products from a products table under each product category. I dynamically called out each product category in buttons, with each products under their specific product category on an HTML table. Each table remains hidden at first because of a class 'hide', but with jquery toggleClass, it gets displayed when their specific product category button is clicked on. But each table has buttons that open a modal and whenever i click on any i want that particular products table under it's product category to remain open. + even if i click on a space within the area or on the table itself and not even on a button, it gets closed. How can i restrict it to just the product category button.
product category buttons on a fresh page load
product displayed when a product category is clicked
<?php
global $number;
global $store_key;
global $product_set;
global $products;
global $query;
global $category;
$store_key = $_SESSION['store_key'];
//$branch_code = $_GET['branch_code'];
$query = "SELECT category_key FROM product_category WHERE store_key = '{$store_key}' ORDER BY category_name ASC";
$category_set = mysql_query($query);
if(!$category_set)
{
die("Database query failed: " . mysql_error().", ".$query);
}
while($category = mysql_fetch_array($category_set)){
?>
<ol id="chaps">
<li><button class="button button-3d button-leaf" ><?php echo ucfirst(get_category($category['category_key']));?></button>
<table id="datatable1" class="table table-striped table-bordered assignments hide" cellspacing="0" width="100%">
<caption>Product Details</caption>
<thead>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Total Pieces</th>
<?php
if($_SESSION['store_key'] == $_SESSION['user_id']){
echo "<th>Action</th>";
}else{
echo "";
}
?>
</tr>
</thead>
<tfoot>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Total Pieces</th>
<?php
if($_SESSION['store_key'] == $_SESSION['user_id']){
echo "<th>Action</th>";
}else{
echo "";
}
?>
</tr>
</tfoot>
<tbody>
<?php
global $number;
global $store_key;
global $product_set;
global $products;
global $query;
$store_key = $_SESSION['store_key'];
//$branch_code = $_GET['branch_code'];
if($_SESSION['store_key'] == $_SESSION['user_id']){
$query = "SELECT DISTINCT product_key,product_name FROM products WHERE store_key = '{$store_key}' AND category_key = '{$category['category_key']}' ORDER BY branch_code,product_name ASC";
$product_set = mysql_query($query);
if(!$product_set)
{
die("Database query failed: " . mysql_error().", ".$query);
}
}else{
$query = "SELECT DISTINCT product_key,product_name FROM products WHERE store_key = '{$store_key}' AND branch_code = '{$_SESSION['branch_code']}' AND category_key = '{$category['category_key']}' ORDER BY branch_code,product_name ASC";
$product_set = mysql_query($query);
if(!$product_set)
{
die("Database query failed: " . mysql_error().", ".$query);
}
}
$number = mysql_num_rows($product_set);
for($count=1;$count<=$number;$count++){
?>
<tr>
<?php $products = mysql_fetch_array($product_set); ?>
<?php echo "<td>{$count}</td>"; ?>
<?php echo "<td>".ucwords($products['product_name'])."</td>"; ?>
<?php
if($_SESSION['store_key'] == $_SESSION['user_id']){
echo "<td>".get_productPieces($products['product_key'])."</td>";
}else{
echo "<td>".get_branchPieces($products['product_key'])."</td>";
}
?>
<?php
if($_SESSION['store_key'] == $_SESSION['user_id']){
echo "<td width='20px'>
<a class='btn btn-warning btn-sm' id='branch' data-toggle=\"modal\" data-target='#add_branchProductModal' href='modals/add_branchProductModal.php?id3={$_SESSION['store_key']}' role='button'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a>";?>
<!--<a class='btn btn-danger btn-sm' href='productdelete.php' role='button'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></a>-->
</td>
<?php
}else{
echo "";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
</li>
</ol>
And my jquery that worked before i discovered my problem
<script>
$("#chaps > li").click(function() {
$(this).find("table.assignments").toggleClass('hide');
});
</script>
then the one i tried to implement to solved the problem, it must be crappy tho cause i'm still learning jquery
<script>
if($("#chaps > li").click()){
$(this).find("table.assignments").toggleClass('hide');
return true;
}else if($("#branch").click()){
$(this).find("table.assignments").toggleClass('hide');
return false;
}
</script>
Try binding the click event handler to the button not to the list item. Since the entire table is contained in the li tag, the handler is triggered anytime anything inside that tag is clicked. See if this works:
<script>
if($("#chaps > li > button.button-leaf").click()){
$(this).find("table.assignments").toggleClass('hide');
return true;
}else if($("#branch").click()){
$(this).find("table.assignments").toggleClass('hide');
return false;
}
</script>
Edit:
In that case try this:
$('#chaps li').each(function () {
$(this).find('button.button-leaf').on('click',function (){
$(this).parents('li').find('table.assignments').toggleClass('hide');
return false;
});
});
$('#branch').on('click', function(){
$(this).parents('table.assignments').toggleClass('hide');
});
I did a similar test example to try it out: https://jsfiddle.net/zstj2nyn/ so it should be working
I have fixed the problem of the table working within a form. I just added an extra <td> field and created a hidden input field within it that will POST a separate tipID for each tip in the table. The entire table is also wrapped with the form tag to get the tipID to POST to the next page.
Now I need to know how make each individual table row send the data from the form kind of like each one being a button or making a hidden button click onclick of one of these table rows.
<form method="post" action="tips.php">
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php if(!empty($tips))
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tip_desc']; echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['datetime']))."</span>"; echo "</br>";
echo date('m-d-y', strtotime($recd['datetime'])); echo"</td><td><input type=";
echo '"hidden" '; echo 'name='; echo '"tip_id" '; echo 'value="';
echo ($recd['tip_id']); echo'"></td></tr>';
}
?>
</tbody>
</table>
</div>
</form>
My next page will use the query below and echo the full tip_desc since a tip can be several hundred characters. It will also have a text area in which an admin can send a message back to the original user.
My PHP and query should look like this on the next page:
<?php
$tipID = $_POST['tipID'];
mysql_query="SELECT * FROM tips WHERE tipID = $tipID";
?>
Just surround your table into a form, place a hidden input field into it.
<form action="tips.php">
<input name="tipID" type="hidden" value="id" />
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php
if(!empty($tips)) {
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tipDescription'];
echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['dateTime']))."</span>";
echo "</br>"; echo date('m-d-y', strtotime($recd['dateTime']));
echo"</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</form>
Have a look at this to make your rows clickable. Working demo
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
Credit: SolutionYogi
Ref: Adding an onclick event to a table row