jquery Datatables with dialog button - php

I am trying to utilize a button that will open a dialog based on the specific row that the button is located in. I have attached my code below.
The button is class is dlg-outletpart-btn:
Here is the jquery javascript portion:
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
} );
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
$( ".dlg-outletpart-btn" ).click(function() {
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
Here is the html with php:
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
$q = $protoFM['EMGSV'] -> newFindCommand('web_outlets');
$q -> addFindCriterion('id_account', '=='.$id_account);
$r = $q->execute();
if(FileMaker::isError($r)){
if($r->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$r->code;
}
}else{
}
} else {
echo "You are not logged in.";
}
?>
<?php
foreach ($r->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($r->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>

I didn't try to test this and there was a lot of cleanup needed so take this with a grain of salt rather than the exact solution.
Before I get into the explanation, there are a couple of points that need to be made:
Stay on top of your indention levels
Poorly indented code is harder to build in and even harder to troubleshoot.
REMEMBER: what you post online reflects on you as a programmer.
Don't use variables with single letters.
Give your variables proper and descriptive names. Single letter names also make it hard to code and hard to troubleshoot.
If you don't need it, don't write it
This is especially true if you're going to post on StackOverflow asking for help. The place where you had an else clause without any code in it should be stripped out of your question and really should be stripped out of your code. If you don't have any tasks to perform within a clause then don't add it. Add it back in when you actually need it. This goes for the closing and immediately opening of the php element. There's no reason to close one php element if you're going to immediately open another. If this is because your knitting two different sections together for the question then clean it out before you submit it.
So, here's the code you can try. Focus on the parts that I commented on in the javascript. The basic idea is:
Make the table your main selector.
You could make the tr element the main selector and it would still give you the index of the tr in the table, but adding the selector to the table itself means if you programmatically add new rows after the DOM has been rendered the jquery method will work for them as well.
Use the this keyword as a starting point.
this will be the button clicked which will allow you to navigate around.
Leverage jquery's navigation methods, in this case closest().
<html>
<head>
<script> /*datatables script function below */
$(document).ready( function () {
$('#table_id_outlets').DataTable();
});
</script>
<script> /*jquery dialog controls for project detail */
$(function() {
$( ".dlgoutletpart" ).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "fade",
duration: 700
},
});
// I changed the element selector to the id of the table element.
// This allows you to specify the selector for the 'on' method to apply to all
// tr elements within the given table and then reference their index relative
// to the overall table.
// I'm using `button` for the method's selector because you have only have
// on button in your table so it de-couples your selector from your class name.
$( "#table_id_outlets" ).on('click', 'button', function() {
debugger;
// this: refers to the button that was clicked
// closest: walks up the node hierarchy till it finds a `tr`
// index(): gives you the index of the `tr` within the table.
// Use the index number however you need.
console.log($(this).closest('tr').index());
var outletID = $(this).attr("data-dlg-outletparts");
$( "#dialog-" + outletID ).dialog( "open" )
});
});
</script>
</head>
<body>
<div>
<p>
<h3>Go Back to main page</h3>
</p>
</div>
<div>
<?php
session_start();
require_once('./includes/php/include_master.php');
if ($_SESSION['authenticated'] == "true") {
$id_account = $_SESSION['ID_Account'];
// Note: you can't put a space between your
$query = $protoFM['EMGSV']->newFindCommand('web_outlets');
$query->addFindCriterion('id_account', '==' . $id_account);
$result = $query->execute();
if(FileMaker::isError($result)){
if($result->code == 401){
echo "No outlets found.";
}else{
echo "Unknown Error:".$result->code;
}
}
} else {
echo "You are not logged in.";
}
foreach ($result->getRecords() as $parts){
$outletID = $parts->getField('ID_Outlet');
$outletData1 = $parts->getField('Image_Data');
$outletData2 = $parts->getField('Image_Data2');
$outletData3 = $parts->getField('Image_Data3');
$outletPart1 = $parts->getField('part1');
$outletPart2 = $parts->getField('part2');
$outletPart3 = $parts->getField('part3');
$outletPart4 = $parts->getField('part4');
$outletPart5 = $parts->getField('part5');
$outletPart6 = $parts->getField('part6');
$outletPart7 = $parts->getField('part7');
$outletPart8 = $parts->getField('part8');
$outletPart9 = $parts->getField('part9');
$outletPart10 = $parts->getField('part10');
echo '<div class="dlgoutletpart" id="dialog-' .$outletParts. '" title="Outlet Parts for '.$outletID.'">';
echo '<p>';
// Use an unordered list here
echo '1. '.$outletPart1.'<br>';
echo '2. '.$outletPart2.'<br>';
echo '3. '.$outletPart3.'<br>';
echo '4. '.$outletPart4.'<br>';
echo '5. '.$outletPart5.'<br>';
echo '6. '.$outletPart6.'<br>';
echo '7. '.$outletPart7.'<br>';
echo '8. '.$outletPart8.'<br>';
echo '9. '.$outletPart9.'<br>';
echo '10. '.$outletPart10.'<br>';
echo '</p>';
echo '</div>';
}
?>
<table id="table_id_outlets" class="display">
<thead>
<tr>
<th>Floor</th>
<th>Area Served</th>
<th>Room Number</th>
<th>Outlet Number</th>
<th>Outlet Gas</th>
<th>Outlet Manufacturer</th>
<th>Outlet Model</th>
<th>Outlet Parts</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->getRecords() as $outlet){
$outletFloor = $outlet->getField('Outet_Floor');
$outletAreaServed = $outlet->getField('Outlet_Area_Served');
$outletRoomNumber = $outlet->getField('Outet_Room_Number');
$outletNumber = $outlet->getField('Outlet_Number_In_Room');
$outletGas = $outlet->getField('Outlet_Gas_Type');
$outletManufacturer = $outlet->getField('Outlet_Manufacturer');
$outletModel = $outlet->getField('Outlet_Model');
echo "<tr>";
echo '<td>' .$outletFloor. '</td>';
echo '<td>' .$outletAreaServed. '</td>';
echo '<td>' .$outletRoomNumber. '</td>';
echo '<td>' .$outletNumber. '</td>';
echo '<td>' .$outletGas. '</td>';
echo '<td>' .$outletManufacturer. '</td>';
echo '<td>' .$outletModel. '</td>';
echo '<td> <button class="dlg-outletpart-btn" data-dlg-outletparts="'.$outletParts.'">Outlet Parts</button>';
}
?>
</tbody>
</table>
</div>
<?php $outlet->getfields('Outlet_Room_Number')?>
</body>
</html>
I didn't test the php portion out, but the jquery definitely works.

Related

AJAX not functioning

I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!
Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>
Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});

Append Data To Tbody AJAX

I have a foreach statement that is adding the data from a DB to my table rows
HTML
<table id="myTable" class="display table center-table" width="100%" >
<thead>
<tr>
<th>Product #</th>
<th>Alternate #</th>
<th>Description</th>
<th>On Hand</th>
<th>Condition</th>
</tr>
</thead>
<tbody id="productResults"> </tbody>
</table>
PHP
$query = $sql . " limit " . $start . "," . $perPage;
$data = $db_handle->runQuery($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
}
$pages = ceil($_GET["rowcount"]/$perPage);
$output = '';
if(!empty($data)) {
$formval = '<input type="hidden" class="pagenum" value="' . $page . '" /><input type="hidden" class="total-page" value="' . $pages . '" />';
foreach($data as $k=>$v) {
$output .= '<tr><td>' . $formval . $data[$k]["wuno_product"] . '</td>';
$formval = '';
$output .= '<td>' . $data[$k]["wuno_alternates"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_description"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_onhand"] . '</td>';
$output .= '<td>' . $data[$k]["wuno_condition"] . '</td></tr>';
}
}
echo $output;
Then in my user view I am adding the data back to the page like this,
JQUERY
<script>
(function($) {
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: { rowcount:$("#rowcount").val() },
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){/* convert to dom element */
$("#productResults").append( data.toElement() );
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
getresult('<?php echo $assetPath; ?>?page='+pagenum);
}
}
});
});
})( jQuery );
</script>
But when it shows up in my page it shows up outside of the table and does not have the html added to it. It looks like this in the page,
8855K5MS21026-B2111212M39029/5-1171313Q4559PROD CODE: 4057911RESTOCKING CHARGE11TAS8732-1C277TEST REPORTS6690H549(W) LAMP CKT99MEC-1MF1 FEET DB9M/F CABLE11T1-GMIL-L-25567E1 GAL JUG2121WL-322914VOLT T-1 BULB100100
Which was the data from the DB just all together... Why would this happen and how can I fix it?
It shows up above the table instead.
firstly, you are attempting to add to a table, but the first portion of your generated code is a form element outside the table structure; any modern browser is going to spot the mistake and add in the assumed missing
</table>
which is why the response is outside a table view.

Asynchronously place data into a dynamically produced div

I have a link that sends a query string to a PHP file that returns data from a Mysql server as JSON. I want to put this JSON data into a DIV that has an ID which matches the query string sent to the PHP file.
Here is my PHP generated Link and DIV
<html>
<head>
<title>BadNoise</title>
</head>
<body>
<form action="Artisttest.php" method="post">
<fieldset>
<p> <input type="submit" value=" Search Our Artists" /> </p>
</fieldset>
</form>
<?php
$con=mysqli_connect("localhost","ee2800","secret","ee2800");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
$result = mysqli_query($con,"SELECT * FROM artist LIMIT 10");
if($_SERVER["REQUEST_METHOD"] == "POST")
echo " <h2>List of BadNoise Artists</h2>
<table border='0'>
<tr>
<th>Artist Number</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Search Songs</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ArtistNumber'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo '<td> <a class="dynamic" href="test4.php?name='. urlencode($row['ArtistNumber']).'">Search Songs</a></td>';
echo "<td><div id=" . $row['ArtistNumber'] . "></div></td>";
echo "</tr>";
}
echo "</table>";
$results->close();
mysqli_close($con);
?>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="general.js"></script>
</body>
Here is the PHP file that returns the JSON data
<?php
$row = $_GET['name'];
echo $_GET['name'];
$dbs = new mysqli("localhost", "ee2800", "secret", "ee2800");
$results = $dbs->query("SELECT * FROM songs WHERE ArtistNumber = {$_GET['name']};");
$rows = array();
while ($r = mysqli_fetch_array($results))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
And here is my attempt at doing this asynchronously with JS.
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
I think I am on the right path but am having trouble targeting the DIV.
Is this what you meant?
</tr><tr><td>1</td><td>Steve</td><td>Perry</td><td> <a id="dynamic" href="test4.php?name=1">Search Songs</a></td></tr><td><div id=1></div></td>
Since you're adding the content on the same row where the click originated, you may not need the id of the div in order to add the content there. Using the link that was clicked determine the parent tr using .closest() the drill down to the div using .find() and .last().
And since you're likely to have multiple links I would recommend using a class .dynamic instead of an id. <td> <a class="dynamic" href="test4 ....
This should do it:
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
UPDATE
The above code has been edited to include DOM ready.
Concept verification --> with DOM ready clicking a a.dynamic link does not navigate to the link.

Unique Value For Each Button

I have two php pages. The first page queries a database and places some data into a form
The second page, grabs the data submited from the previous page and displays the data.
THE ISSUE:
On the second page, the information is displayed in a table. At the end of each row, there is a "information" button that allows the user to click and see more details related to the data in that particular column. For some reason, the information button for every record in the table is holding the value of the first record returned in the database query. In other words no matter what button I click on in the table, it always relates to the first record returned in the query.
I'm hoping someone can help me find a solution to linking each "information" button to each unique record. In other words If I click the info button in row one, it will display the data for the record related to row 1...etc. Here's my code.
PAGE 1
<?php
$query = mysql_query ("SELECT * from cust_data group by cabinet_number ORDER by cabinet_number ASC");
WHILE ($rows = #mysql_fetch_array($query)) {
if (($rows['account_number']=="") &&
($rows['customer_first_name']=="") &&
($rows['customer_last_name']=="") &&
($rows['company_name']=="")) {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_green.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['cabinet_number'].'" id="submit">
</form>';
} else if ($rows['cabinet_number']!=="") {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_red.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['company_name'].'" id="submit">
</form>';
}
}
}
PAGE 2:
GRABS THE DATA IN PAGE ONE AND PLACES IT IN A TABLE. WHEN THE 'INFO' BUTTON IS CLICKED, MORE INFORMATION IS DISPLAYED IN A JQUERY POPUP
db_connect();
$cabinet_number = $_GET['cabinet_number'];
$company_name = $_GET['company_name'];
$query = #mysql_query ("SELECT * FROM cust_data WHERE cabinet_number = '$cabinet_number' ");
WHILE ($rows = #mysql_fetch_array($query)) {
echo'<tr>
<td><font size="4">'; echo $rows['account_number']; echo'</font></td>
<td><font size="4">'; echo $rows['customer_first_name']; echo '</font></td>
<td><font size="4">'; echo $rows['customer_last_name']; echo '</font></td>
<td><font size="4">'; echo $rows['company_name']; echo '</font></td>
<td><font size="4">'; echo $rows['cabinet_number']; echo'</font></td>
<td><font size="4">'; echo $rows['key_tag_number']; echo'</font></td>';
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo '<td><font size="4">';
echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
{
echo '<td><font size="4">'; echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
echo '</tr>';
echo '<div class="well" style="display:none;margin:1em;" class="my_modal">';
echo '<img src="images/hdc_logo_transparent.png"><br>';
echo '<div style="height:23px; width:100%; background-color:black"> <h4><font color="#FFFFFF">',' ', 'Cabinet: ', $id, '</font></h4></div>';
echo '<p>';
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Power: ', $rows['power_circuit'];
echo '<br>';
echo'<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port1'];
if ($rows['switch_and_port2'] =="") {
echo '';
} else if ($rows['switch_and_port2'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port2'];
}
if ($rows['switch_and_port3'] =="") {
echo '';
} else if ($rows['switch_and_port3'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port3'];
}
if ($rows['switch_and_port4'] =="") {
echo '';
} else if ($rows['switch_and_port4'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port4'];
}
echo '</p>';
echo'</div></form>';
}
echo'<script>
$(document).ready(function() {
$(".my_modal_open").click(function(){
$(this).closest("tr").next(".my_modal").popup({"autoopen": true});
});
});
});
</script>
</body>
</html>';
}
The issue is that you are setting the same id attribute to all the modals (which is invalid HTML markup) and expecting the click handler on the button to figure out which one to open.
UPADTE
Another issue with your markup is that you can't have <div>s as siblings of a table row, it will produce unexpected results as browsers will attempt to fix the markup and rearrange the elements, you could place the divs inside a td or use a second loop to build them.
Now I also did some digging in your popup plugin and I must say it's not very well implemented, I would recommend you look for another one. That being said I did manage to get it working, here's what you need to do:
Set an unique id for each of the modal divs, if you have some sort of id in your database data you can use that, if not then you can set up a counter variable inside the loop:
echo '<div class="well" id="my_modal'.$rows['id'].'">';
Use the same id as the class for the button that should open the modal but add "_open" as a suffix:
echo '<input type = "image" src="images/view_details.png" height="16" width="16" class="my_modal'.rows['id'].'_open">
You can now initialize the popup plugin on your divs and it will automatically assign the open action to the corresponding button:
echo'<script>
$(document).ready(function () {
$("[id^=\'my_modal\']").each(function () {
$(this).popup();
});
});
</script>';
That should fix the modal problem, here's a working demo.
Now I also have a couple observations about your code:
You should avoid the use of inline styles and as I mentioned earlier the <font> tag should be replaced for proper CSS, I would also suggest using CSS padding/margin to add space between words instead of
This type of code:
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
can be optimized to just:
if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
echoing an empty string produces no output whatsoever and there's no need for an elseif

jquery calculation works in jsfiddle example, but not in main code

I have a jsfiddle here where a jquery function is used in able to make a calculation between the number entered in the text input and subtracting the number with the "Total Marks" number per question.
Have a play around in the jsfiddle, in question 1 change the values in the text input and you will see the total marks change with in the same question block. For question 2 it is a readonly box but the reason it is readonly is because it is a single answer. If a question has a single answer then the text input should be readonly else if multiple answers then it should not be readonly.
The fact is though is that I want the jquery function to work with the code below but it doesn't at the moment. These are the problems I have which needs to be fixed:
The total marks should not equal 5, it should equal the value of $searchMarks[$key], as each question could have a different total marks
At the moment for the code below it does not perform the calculation
Finally it is not making the text input readonly if question only contains single answer.
My question is that how should the code below be setup so that it can work exactly the same as the jsfiddle?
Below is the code:
<script type="text/javascript" src="jquery/jquery-1.7.min.js"></script>
<script type="text/javascript" src="jquery/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="jquery/basic.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $inputs = $('input.individualMarks');
$inputs.filter(function() {
return $(this).prop('readonly') === true;
}).each(function() {
var $input = $(this);
});
$inputs.filter('[data-q_group]').keyup(function() {
var $group = $inputs.filter('[data-q_group="' + $(this).data('q_group') + '"]');
var $marks = $group.eq(0).closest('tr').find('td.noofmarkstd');
var markVal = <?php $searchMarks ?>;
$group.each(function() {
markVal -= ($(this).val() || 0)
})
$marks.text(markVal)
})
});
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<?php
echo "<table border='1' id='markstbl'>
<tr>
<th class='questionth'>Question No.</th>
<th class='questionth'>Question</th>
<th class='answerth'>Answer</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Total Marks</th>
</tr>\n";
$previous_question_id = null;
$rowspans = array_count_values($searchQuestionId);
foreach ($searchQuestionContent as $key=>$question) {
// removed logic, not necessary to set empty strings if you're skipping them
echo '<tr class="questiontd">'.PHP_EOL;
if ($previous_question_id != $searchQuestionId[$key]) {
echo '<td class="questionnumtd" name="numQuestion" rowspan="'.$rowspans[$searchQuestionId[$key]].'">'.htmlspecialchars($searchQuestionId[$key]).'</td>' . PHP_EOL;
echo '<td class="questioncontenttd" rowspan="'.$rowspans[$searchQuestionId[$key]].'">'.htmlspecialchars($question).'</td>' . PHP_EOL;
}
echo '<td class="answertd" name="answers[]">';
echo $searchAnswer[$key];
echo '</td>' ;
echo '<td class="answermarkstd"><input class="individualMarks" name="answerMarks[]" id="individualtext" type="text" /></td>' . PHP_EOL;
if ($previous_question_id != $searchQuestionId[$key]) {
echo '<td class="noofmarkstd" rowspan="'.$rowspans[$searchQuestionId[$key]].'">'.htmlspecialchars($searchMarks[$key]).'</td>' . PHP_EOL;
}
// moved this to the end
if ($previous_question_id != $searchQuestionId[$key]) {
$previous_question_id = $searchQuestionId[$key];
}
}
echo '</tr>';
echo "</table>" . PHP_EOL;
?>
</form>
Your code behaved the same locally as it did in jsFiddle after enclosing it within $(document).ready (As mentioned in a comment above).
$(function() {<your code>});
Maybe you forgot to src jquery?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

Categories