How do I toggle <td> 'table data cells' in Javascript? - javascript

So I need to be able to click to show/hide table data cells, however, after trying multiple functions for toggling their display I've been unable to progress forward in my attempts.
Although I've tried several different functions I keep getting the same error:
Uncaught ReferenceError: toggle_visibilityOn is not defined
at HTMLTableCellElement.onclick
Here is the latest iteration of my code in PHP.
if($job_type != 'Maintenance'){ ?>
<tr>
<!--<td><a href="edit-job-2.php?job=<?php echo $job_id; ?>">-->
<td onclick = "toggle_visibilityOn(<?php echo $job_id; ?>)"><?php echo $job_id; ?>
<td id = "billingticket<?php echo $job_id; ?>"><?php echo $billing_ticket; ?></td>
<td id = "billing_status<?php echo $billing_status; ?>"><?php echo $billing_status; ?></td>
<td id = "job_date<?php echo $job_date; ?>"></td>
<td id = "drilling_contractor<?php echo $drilling_contractor; ?>"><?php echo $drilling_contractor; ?></td>
<td id = "job_type<?php echo $job_type; ?>"><?php echo $job_type; ?></td>
<td id = "lease_name<?php echo $lease_name; ?>"><?php echo $lease_name; ?></td>
<td id = "job_status<?php echo $job_status; ?>"><?php echo $job_status; ?></td>
</td>
<tr>
<?php }
I have commented out the previous attempts.
Here is the Javascript portion of the code:
function toggle_visibilityOn()
{
document.getElementById("billing_status<?php echo $billing_status; ?>").style.display = "block";
document.getElementById("job_date<?php echo $job_date; ?>").style.display = "block";
document.getElementById("drilling_contractor><?php echo $drilling_contractor; ?>").style.display = "block";
document.getElementById("job_type<?php echo $job_type; ?>").style.display = "block";
document.getElementById("lease_name<?php echo $lease_name; ?>").style.display = "block";
document.getElementById("job_status<?php echo $job_status; ?>").style.display = "block";
document.getElementById("billingticket<?php echo $job_id; ?>").setAttribute('onclick','toggle_visibilityOff()');
document.getElementById("billingticket<?php echo $job_id; ?>");
}
function toggle_visibilityOff()
{
document.getElementById("billing_status<?php echo $billing_status; ?>").style.display = "none";
document.getElementById("job_date<?php echo $job_date; ?>").style.display = "block";
document.getElementById("drilling_contractor<?php echo $drilling_contractor; ?>").style.display = "block";
document.getElementById("job_type<?php echo $job_type; ?>").style.display = "none";
document.getElementById("lease_name<?php echo $lease_name; ?>").style.display = "none";
document.getElementById("job_status<?php echo $job_status; ?>").style.display = "none";
document.getElementById("billingticket<?php echo $job_id; ?>").setAttribute('onclick','toggle_visibilityOn()');
document.getElementById("billingticket<?php echo $job_id; ?>");
}
I know I'm doing something wrong, and I'm almost sure it has to do with the Id tags, but I'm no closer to figuring it out than I was two days ago.
Note: I'm fixing and editing preexisting code so I'm not familiar with everything that's going on. I'm aware the answer may lie elsewhere.
To anyone who reads this: Thank you for your time.

There is a lot we can do to make this better. First, you shouldn't echo the jobID in the javascript -- you should pass the value via the onClick method. Next, we can combine both of your toggle methods into one simplified version. Lastly, unless you want your table columns to be stacked, you won't want to use display: block for the toggleOn -- use display: inline-block or display: inline.
Here's an example with your PHP removed so that it can demonstrate the functionality of the javascript.
function toggle_visibility(jobID) {
const billingTicket = document.getElementById("billingticket" + jobID);
const style = (billingTicket.style.display === "none") ? "inline-block" : "none";
billingTicket.style.display = style;
document.getElementById("billing_status" + jobID).style.display = style;
document.getElementById("job_date" + jobID).style.display = style;
document.getElementById("drilling_contractor" + jobID).style.display = style;
document.getElementById("job_type" + jobID).style.display = style;
document.getElementById("lease_name" + jobID).style.display = style;
document.getElementById("job_status" + jobID).style.display = style;
}
<table>
<tr>
<td onclick="toggle_visibility(5)">JOBID 5</td>
<td id="billingticket5">Billing Ticket</td>
<td id="billing_status5">Billing Status</td>
<td id="job_date5">Job Date</td>
<td id="drilling_contractor5">Drilling Contractor</td>
<td id="job_type5">Job Type</td>
<td id="lease_name5">Lease Name</td>
<td id="job_status5">Job Status</td>
</tr>
</table>
Just put your PHP back into the table structure here and you should be good to go.
If this is exactly how you want the data in your table to be laid out, we can simplify this even more:
function toggle_visibility(element) {
[...element.parentNode.children].splice(1).forEach(column => {
column.style.display = column.style.display === 'none' ? "inline-block" : "none";
});
}
<table>
<tr>
<td onclick="toggle_visibility(this)">JOBID 5</td>
<td>Billing Ticket</td>
<td>Billing Status</td>
<td>Job Date</td>
<td>Drilling Contractor</td>
<td>Job Type</td>
<td>Lease Name</td>
<td>Job Status</td>
</tr>
</table>
This is even better because it doesn't require the elementID's, and so you also won't need to clutter your PHP file with all those echos.
What I'm doing here is using the context of this to pass in the element that was clicked. Then we get an array of the element's siblings by using spread syntax to create an array from the children object of the parentNode, and splice the array to remove the first child from the array, leaving us with an array that contains all of the siblings of the element that was clicked. Finally we loop through each member of the array to toggle the display style of each sibling.
If you need a button that can toggle all of these types of rows, try this example:
function toggle_visibility(element) {
[...element.parentNode.children].splice(1).forEach(column => {
column.style.display = column.style.display === 'none' ? "inline-block" : "none";
});
//check if all rows are hidden/shown to update button label
let comparison,
shouldUpdateButtonLabel = true,
rows = document.getElementsByTagName("tr");
[...rows].forEach(row => {
if (!comparison) comparison = row.children[1].style.display;
else if (row.children[1].style.display !== comparison) shouldUpdateButtonLabel = false;
});
if (shouldUpdateButtonLabel) {
let button = document.getElementById("toggleAll");
button.innerHTML = button.innerHTML === "Hide All" ? "Show All" : "Hide All";
}
}
function toggleAll(button) {
const style = button.innerHTML === "Hide All" ? "none" : "inline-block";
button.innerHTML = button.innerHTML === "Hide All" ? "Show All" : "Hide All";
let rows = document.getElementsByTagName("tr");
[...rows].forEach(row => {
[...row.children].splice(1).forEach(column => {
column.style.display = style;
});
});
}
td {
display: inline-block;
}
<table>
<tr>
<td onclick="toggle_visibility(this)">JOBID 5</td>
<td>Billing Ticket</td>
<td>Billing Status</td>
<td>Job Date</td>
<td>Drilling Contractor</td>
<td>Job Type</td>
<td>Lease Name</td>
<td>Job Status</td>
</tr>
<tr>
<td onclick="toggle_visibility(this)">JOBID 6</td>
<td>Billing Ticket</td>
<td>Billing Status</td>
<td>Job Date</td>
<td>Drilling Contractor</td>
<td>Job Type</td>
<td>Lease Name</td>
<td>Job Status</td>
</tr>
<tr>
<td onclick="toggle_visibility(this)">JOBID 7</td>
<td>Billing Ticket</td>
<td>Billing Status</td>
<td>Job Date</td>
<td>Drilling Contractor</td>
<td>Job Type</td>
<td>Lease Name</td>
<td>Job Status</td>
</tr>
</table>
<button id="toggleAll" onclick="toggleAll(this)">Hide All</button>

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>

Unable to store particular target values in jQuery

$(document).ready(e => {
$(".test").click(e => {
textvalue = displayData(e);
console.log(textvalue); //prints the array
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Email</th>
<th>Contact</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>DummyName</td>
<td>20</td>
<td>Female</td>
<td>DummyEmail</td>
<td>DummyContact</td>
<td>DummyDepartment</td>
<td class="test">Click</td>
</tr>
<tr>
<td>DummyName2</td>
<td>22</td>
<td>Female</td>
<td>DummyEmail2</td>
<td>DummyContact2</td>
<td>DummyDepartment2</td>
<td class="test">Click</td>
</tr>
</tbody>
</table>
</body>
</html>
I'm using jQuery to update onscreen values in a form. Complete beginner at this.
$(document).ready(e =>{
$(".btnedit").click(e =>{
textvalues = displayData(e);
let sname = $("input[name*='name_type");
let sage = $("input[name*='age_type");
let sgender = $("input[name*='gender_type");
let semail = $("input[name*='email_type");
let scontact = $("input[name*='contact_type");
let sdept = $("input[name*='dept_type");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
semail.val(textvalues[3]);
scontact.val(textvalues[4]);
sdept.val(textvalues[5]);
});
});
function displayData(e){
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for(const value of td){
if(value.dataset.name == e.target.dataset.name)
{
//console.log(value);
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
I need to get the data stored in a table onto the inputs of the form, in order for the user to update it further. The user clicks on a record to edit it(which is displayed on the page).
The record values are stored in the array textvalues. Problem is the entire table values get stored in the array instead of just the single record.
In value.dataset.name, name is a column from the table which I'm using as the primary key (I know it's wrong, but just going with it for now).
Edit: Original table code:
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['name'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['age'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['gender'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['email'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['contact'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['department'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><i class="fas fa-edit btnedit"></i></td>
</tr>
<?php
}
Your code works fine except one little thing: all your input selectors lack closing quote and bracket, e.g. this is wrong (jQuery 3.3.1 throws error):
let sname = $("input[name*='name_type");
But this is right:
let sname = $("input[name*='name_type']");
Otherwise, it works just fine (well, certain optimizations can be done, that's true, but still it works as is) -- if I have guessed your HTML structure correctly, see example below. (Disclaimer: this is by no means a good piece of code with best pracrices etc. This is just a reproduction of original task with minimal fix to make it work.)
$(document).ready(e => {
$(".btnedit").click(e => {
textvalues = displayData(e);
let sname = $("input[name*='name_type']");
let sage = $("input[name*='age_type']");
let sgender = $("input[name*='gender_type']");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody">
<tr>
<td data-name="1">a1</td>
<td data-name="1">b1</td>
<td data-name="1">c1</td>
<td><button class="btnedit" data-name="1">edit</button></td>
</tr>
<tr>
<td data-name="2">a2</td>
<td data-name="2">b2</td>
<td data-name="2">c2</td>
<td><button class="btnedit" data-name="2">edit</button></td>
</tr>
</tbody>
</table>
Type: <input type="text" name="name_type" /><br />
Age: <input type="text" name="age_type" /><br />
Gender: <input type="text" name="gender_type" />
Possible reason of could be this: data-name is invalid everywhere in your table. If that's not the case, please share some more code. Minimal yet complete example would be great.
Update: in your example HTML I see no data-name attributes at all, and clickable element also does not have it. So, your selector $('#tbody th td') matches all TDs, and that's why you see whole table in output.
So, look at the example above and do the same with data-name: every <td> and the button on one row have the same value in that attribute.

Why this javascript trigger is not working?

I am trying to show abox when a table row is clicked:
Js
$("#rowID").click(function(){
var User = document.getElementById("userID");
var Box = document.getElementById("userBox");
document.Box.style.display = "block";
});
HTML
<tr id="rowID" href="#">
<td id="userID"><?php echo $datum['ID']; ?></td>
<td><?php echo $datum['Account']; ?></td>
<td><?php echo $datum['Date']; ?></td>
<td><span class="label label-warning">Pending</span></td>
<td><?php echo $datum['Email']; ?></td>
</tr>
You don't need another prepending document. to Box. You're basically saying document.document.getElementById('userBox').
Also, you might aswell just make everything JQuery since you're using it to assign an EventListener to #rowId.
Also, since there will be multiple rows, you might want to make #rowID into a class, e.g. .row since an ID should be uniquely identifiable to one element.
$(".row").click(function(){
var user = $("#userID");
var box = $("#userBox");
box.show();
});
#userBox {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="row" href="#">
<td id="userID">Hello</td>
<td>World!</td>
</tr>
<tr class="row" href="#">
<td id="userID">Foo</td>
<td>Bar</td>
</tr>
</tbody>
</table>
<div id="userBox">I'm a box!</div>

Hide row depending on a html table cell value

I have a table that displays data from database and i have a cell with a simple arithmetic function.
I want to hide the entire row where the result of the sum is zero(if $sold value is zero).
<input type="button" id="btnHide" Value=" Hide Empty Rows " />
...
<tbody>
<?php }
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['value1']+$row['value2']);
{ ?>
<tr>
<td><?php echo $row['contract'] ?></td>
<td><?php echo (round($row['value1'], 2)) ?></td>
<td><?php echo (round($row['value2'],2 )) ?></td>
<td><?php echo ((round($sold, 2))+0) ?></td>
</tr><?php } } ?>
</tbody>
I found some code to hide all rows where it have empty cells, but it's not what i want. Thx for help.
$(document).ready(function() {
$("#gdRows td").each(function() {
var cellText = $(this).text();
if ($.trim(cellText) == '') {
$(this).css('background-color', 'cyan');
}
});
$('#btnHide').click(function() {
$("#gdRows tr td").each(function() {
var cell = $.trim($(this).text());
if (cell.length == 0) {
$(this).parent().hide();
}
});
});
$('#btnReset').click(function() {
$("#gdRows tr").each(function() {
$(this).show();
});
});
});
Add a class to those cells for simplification
<td class="sold"><?php echo ((round($sold, 2))+0) ?></td>
Then use filter()
$("td.sold").filter(function() {
return +$(this).text().trim() === 0;
}).parent().hide();
You could also do the same thing in php by adding a hidden class to the row if $sold is zero and add a css rule for hidden class
PHP
<tr class="<?= $sold == 0 ? 'hidden' :'';?>">
The following function will loop through all <tr> in a table and find the 4th cell within the row. If that cell contains a value that evaluates to zero, then the row becomes hidden.
$("table tr").each(function() {
var sold = $(this).find(":nth-child(4)");
if (parseFloat(sold.text()) === 0)
$(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Contract</td>
<td>123</td>
<td>456</td>
<td>789</td>
</tr>
<tr>
<td>Contract</td>
<td>123</td>
<td>456</td>
<td>0</td>
</tr>
<tr>
<td>Contract</td>
<td>0.123</td>
<td>0.456</td>
<td>0.0</td>
</tr>
<tr>
<td>Contract</td>
<td>0.123</td>
<td>0.456</td>
<td>0.789</td>
</tr>
</table>

Parse (string)table with parent tr´s into array

I have a string with a table inside; my problem is to put the parent tr´s (according their childs) into array (for later using it is not important whether array is one- or multidimensional)
The table looks like this:
<tr><td class="boys" colspan="4"></td></tr>
<tr><td class="indoor" colspan="4"></td></tr>
<tr class="toy">
<td class="article">Ball</td>
<td class="color">Red</td>
<td class="size">big</td>
<td class="price">10</td>
</tr>
<tr class="toy">
<td class="article">Puzzle</td>
<td class="color">colored</td>
<td class="size">medium</td>
<td class="price">5</td>
</tr>
<tr><td class="outdoor" colspan="4"></td></tr>
<tr class="toy">
<td class="article">Inliner</td>
<td class="color">black</td>
<td class="size">5</td>
<td class="price">15</td>
</tr>
<tr class="toy">
<td class="article">Pool</td>
<td class="color">white/blue</td>
<td class="size">big</td>
<td class="price">25</td>
</tr>
<tr><td class="all" colspan="4"></td></tr>
<tr class="toy">
<td class="article">Book</td>
<td class="color">colored</td>
<td class="size">small</td>
<td class="price">2</td>
</tr>
and same tr/td construct for girls.
With
$html = str_get_html($e);
$toys= array();
foreach ( $html->find('tr[class=toy]') as $toy) {
$item['article'] = trim($toys->find('td', 0)->plaintext);
$item['color'] = trim($toys->find('td', 1)->plaintext);
$item['size'] = trim($toys->find('td', 2)->plaintext);
$item['price'] = trim($toys->find('td', 3)->plaintext);
$toys[] = $item;
}
How can i get both parents? So that array looks like
[0] => Array
(
[sex] => boys
[place] => indoor
[article] => Puzzle
[color] => colored
[size] => medium
[price] => 5
)
trying to get it with
$item['place'] = $toys->find('tr.toy', 0)->plaintext;
give wrong results...
You haven't posted the complete table structure (for girls as well), so I assume it looks like this:
<table id="products">
<tr><td class="boys" colspan="4"></td></tr>
<tr><td class="indoor" colspan="4"></td></tr>
<tr class="toy">...</tr>
<tr><td class="outdoor" colspan="4"></td></tr>
<tr class="toy">...</tr>
<tr><td class="girls" colspan="4"></td></tr>
<tr><td class="indoor" colspan="4"></td></tr>
<tr class="toy">...</tr>
<tr><td class="outdoor" colspan="4"></td></tr>
<tr class="toy">...</tr>
</table>
As I wanted to familiarize with the Simple DOM Parser Package, this was a welcome exercise for me. I leave the code as is. I hope it isn't against SO-Rules to omit explanations. So if an angry admin disagrees, or the OP wants some additional info, leave another answer here and I'll provide it in the future. Please regard the table-attribute id.
$ret = $html->find("table[id=products] tr");
$items = array();
$item = NULL;
foreach($ret as $r)
{
echo "got in the loop<br>";
$class = $r->getAttribute("class");
echo "class: $class<br>";
if (strlen(trim($class)) == 0)
{
echo "We have a <tr> without a class<br>";
$td = $r->firstChild();
$class = $td->getAttribute("class");
echo "The <td>-child should either have class boys,girls, indoor or outdoor<br>";
if (strcasecmp($class, "girls") == 0 ||
strcasecmp($class, "boys") == 0)
{
$sex = $class;
echo "It's a $sex<br>";
}
else
{
if (strcasecmp($class, "indoor") == 0 ||
strcasecmp($class, "outdoor") == 0)
{
$place = $class;
echo "Item is meant for $place-usage<br>";
}
}
}
else
{
$childs = $r->childNodes();
$item = array();
$item["place"] = $place;
$item["sex"] = $sex;
echo "Creating new item for $place-$sex<br>";
foreach($childs as $child)
{
$class = $child->getAttribute("class");
$item[$class] = $child->innertext;
echo "Item attribute $class with ".$child->innertext."<br>";
}
array_push($items, $item);
}
}
echo "<pre>";
print_r($items);
echo "</pre>";

Categories