Insert an image depending on table content - javascript

I have a database item (called fairtrade) that has one of the following values: Yes, No, N/A.
These are displayed in the front end in a <table>.
<table class="data-table" id="product-attribute-specs-table">
<colgroup>
<col width="25%"></col>
</colgroup>
<tbody>
<tr class="last odd">
<th class="label">Fairtrade</th>
<td class="data last">N/A</td>
</tr>
</tbody>
</table>
If the database displays YES in the content I would like to display an image. If the database displays No or N/A I would like to hide that particular table row.
Can I use Javascript / JQuery to make the above happen. I'm not even sure if its possible.
Any help would be appreciated.

Well, you will need something like PHP to fetch the data from the database since JavaScript alone is not capable of doing that.
When that has been done you can use the server side language to insert the images depending on what data you get from the database while it's rendering the table.
If the table data is rendered for you you can use JavaScript to show the image depending on a value in a cell.
A simple jQuery example would probably be something like this (sorry, not tested, from the top of my head so might contain errors)
$("td").each(function(){
if($(this).text() == "YES"){
//code to show image here
}
});

Given your HTML, the following code should work for you.
$('.data-table tr .data').each(function() {
if ($(this).text() == 'Yes') {
// show your image
}
else {
$(this).closest('tr').hide();
}
});
Example fiddle

Related

JQuery/Javascript my function is not running when pressing button

I have a button, when I click I want it to get all data from the row. My .php file (i also have php code not included here) looks like so (I trimmed out the table for stackoverflow)
<tr class='rowdata'>
<td>Bob</thd>
</tr>
<input type='submit' class='getRow' value='ClickMe'>
<script>
$(".getRow").click(function() {
var rowOfData = $(this).closest(".rowdata");
alert(rowOfData.text());
});
</script>
Right now I click and nothing happens. Any ideas? The . prefix means it is searching for class.
Well first, have you checked your developer's console (F12) to see if you have any errors. Are you sure you've referenced the JQuery library.
Next, even with JQuery referenced, .closest() is going to search the ancestor elements of the element you call it on. If your button is not a descendant of the element you wish to find, you won't find it.
Now, assuming that .closest() does find your row, you are then asking for the .text() in the entire row. This may be what you want, but it's seems more likely that you'd want data cell by cell.
Also, your button is a submit button which is used for submitting form data, but it doesn't appear that that's what you're doing here. If that's the case, use a regular button.
And, your HTML isn't valid as you have a bad closing tag for your cell.
So, correcting all that:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class='rowdata'>
<td>Bob</td>
<td>Smith</td>
<td><input type='button' class='getRow' value='ClickMe'></td>
</tr>
</table>
<script>
$(".getRow").click(function() {
var rowOfData = $(this).closest(".rowdata");
alert(rowOfData.text()); // Gets all the text in the row
alert($("td:first-child", rowOfData).text()); // Gets just first cell
});
</script>

In Ember.js why does 'afterRender' not trigger on a redraw?

I'm trying to call a function when new data gets added to a table in a view, but it's not working. I'm using Ember.js 2.5
I have two models, client and user. A client has many users.
My view to list clients looks like this:
<table class="table table-striped" id="admin-table">
<thead>
<tr>
<th>Primary User</th>
<th>User Email</th>
<th>Join Date</th>
</tr>
</thead>
<tbody>
{{#each model as |client|}}
<tr>
<td>{{client.primaryUser.name}}</td>
<td>{{client.primaryUser.email}}</td>
<td>{{client.createdAt}}</td>
</tr>
{{/each}}
</tbody>
</table>
primaryUser is a computed property containing the first user for each client.
primaryUser: Ember.computed('users', function(){
return this.get('users.firstObject');
})
Problem
I'm using the jquery tablesorter library which adds sorting and filtering to the table. Because the primaryUser get's loaded by AJAX I need to call $('#admin-table').trigger('update') when new data is added in order to have the library index the new information.
Here's what I'm doing:
modelObserver: function() {
Ember.run.next(this, this.updateTable);
}.observes('model.#each.primaryUser')
I've tried both run.next, and run.scheduleOnce('afterRender'..) and the result is always the same. The updateTable function triggers before all of the primaryUser objects are rendered.
Here's what happens if I put a debugger within this.updateTable:
it only triggers once, when a cached user (me) is rendered. The empty cells in this table populate a few ms later when the rest of the user information is ajaxed in, but updateTable never re-runs.
I can confirm at this point that the other primary user fields are not in the DOM:
Help
Is there a way to trigger an event once all objects have been rendered? I've using Ember.run.sync() as mentioned in this answer, but it didn't help.
Everything's fine but you need to manually check if all users are rendered. There's no other option. The code would look like this I think. It's a bit primitive, but I think you get the idea that you just can check the DOM.
modelObserver: function() {
var areRendered = [];
Ember.$('table#admin-table tr').each(function (index, element) {
$(element).find('td').each(function (anotherIndex, anotherElement) {
if (anotherIndex <= 1) { //This is because according to your screenshot you don't have to check all the cells, just first two if I'm not mistaking.
if (anotherElement.text()) {
areRendered.push(true);
} else {
areRendered.push(false);
}
}
});
});
if (!areRendered.contains(false)) { //Checking if there were any element without data.
Ember.run.next(this, this.updateTable);
}
}.observes('model.#each.primaryUser')
Hope it helps!

How to prevent PHP Post Max Size being exceeded on a Form submission

I have a FORM on a PHP web page that accepts a table of data (editable-grid) which the end-user is in control of in that they can add as many rows as they like. One of the fields is also a TEXTAREA which means each row has a variable size.
If the post is too large however, it will be rejected by the server and all the target page will see is an empty $_POST. Worse, if the user navigates back to the input page, it will show its initial empty state, losing all data entered and annoying the end-user to say the least.
I could increase the POST_max_size setting in PHP, but all that will do is push the boundary at which it will fail.
I could also check in JavaScript what the size of the post will be, PRIOR to them submitting the form, ideally as they add each row or change the textarea content, but I'm not sure how accurate or slow that will be. It also means they would have to remove some data or rows.
The only other option I can think of is to submit each row individually in a hidden FORM, through AJAX, once they click the Submit button. I'm not sure it is a good idea to replace one post with hundreds of posts to the server.
Any other ideas?
Instead of sending the entire datagrid you can just send the edited row as if it were a single form using javascript. If you send each row in a loop with ajax even if it is not edited you can choke the server in the same way as if you were sending the entire datagrid. Instead of sending 20k rows of data with just one column modified, just send one row when the user leaves the textarea.
I don't know how you manage the editing events but with jQuery (for the sake of simplicity) could be something like this.
$(document).ready(function() {
$('textarea, input').on('blur', function(e) {
var $row = $(this).closest('tr')
var data = {
id: $row.data('id'),
input: $row.find('td input').val(),
textarea: $row.find('td textarea').val()
};
// e.g. foo.php/1
$.post("foo.php/" + data.id, data)
.success(function() { /* silent success */ })
.fail(function() { alert('Error') })
});
});
with html
<table>
<tbody>
<tr data-id="1">
<td><input /></td>
<td><textarea></textarea></td>
</tr>
<tr data-id="2">
<td><input /></td>
<td><textarea></textarea></td>
</tr>
<tr data-id="3">
<td><input /></td>
<td><textarea></textarea></td>
</tr>
</tbody>
</table>
example jsfiddle https://jsfiddle.net/vt0a0udx
ps: sorry for the bad english.
try to change this value in php.ini
max_input_vars = 1000 to 10000

Why AJAX response is not in sortable manner

I am using sorttable.jsfor table sorting and my table is updated in every 3 sec by ajax response but the response is not in sorted manner as i expect it to be.
Index page
<div id="resDiv">
<table id="myTable1" class="sortable">
<thead>
<tr><th id="person">Person</th><th id="monpay">Monthly pay</th></tr>
</thead>
<tbody>
<tr><td>Jan Molby</td><td>£12,000</td></tr>
<tr><td>Steve Nicol</td><td>£8,500</td></tr>
<tr><td>Steve McMahon</td><td>£9,200</td></tr>
<tr><td>John Barnes</td><td>£15,300</td></tr>
</tbody>
<tfoot>
<tr><td>TOTAL</td><td>£45,000</td></tr>
</tfoot>
</table>
</div>
Append new table data
ajax response is :
<table id="myTable" class="sortable">
<thead>
<tr><th>Person</th><th>Monthly pay</th></tr>
</thead>
<tbody>
<tr><td>prabha Molby</td><td>£12,000</td></tr>
<tr><td>abcd Nicol</td><td>£8,500</td></tr>
<tr><td>steev McMahon</td><td>£9,200</td></tr>
<tr><td>John Barnes</td><td>£15,300</td></tr>
</tbody>
<tfoot>
<tr><td>TOTAL</td><td>£55,000</td></tr>
</tfoot>
</table>
JavaScript
$(function() {
$("#ajax-append").click(function() {
setInterval(function() {
var request = $.get("assets/replacecontent.jsp", function(html) {
alert(html);
$('#resDiv').html(html);
var newTableObject = document.getElementById("myTable");
alert(newTableObject);
sorttable.makeSortable(newTableObject);
// alert($("#myTable").length);
});
}, 3000);
});
});
Now if any time i sort the ajax response it get sorted but after another response it again change it's order but i want it sorted as previous one.
I think you should have read what the sorttable.js faq says:
Sorting the table when the page is loaded
Lots of people ask, "how do I make sorttable sort the table the first
time the page is loaded?" The answer is: you don't. Sorttable is about
changing the HTML that is served from your server without a page
refresh. When the page is first served from the server, you have to
incur the wait for it to be served anyway. So, if you want the table
sorted when a page is first displayed, serve the table in sorted
order. Tables often come out of a database; get the data from the
database in a sorted order with an ORDER BY clause in your SQL. Any
solution which involves you running sorttable as soon as the page
loads (i.e., without user input) is a wrong solution.
But they also state a solution for that:
//Find the TH you want to use, maybe you can store that using an event handler before
var myTH = document.getElementsByTagName("th")[0];
//Then sort it
sorttable.innerSortFunction.apply(myTH, []);
But to that you will have to find the column your user clicked on before, and to be honest I have not found any way using the sorttable api directly. Maybe use some kind of click event handler and store the th that was clicked last.

jQuery cleaning HTML table

This is my table:
<tr class=stuff>
<td id=id></td>
<td id=city_id></td>
<td id=temp></td>
<td id=date></td>
</tr>
This is my Javascript:
<script>
$(document).ready(function() { // waits when document is ready
$('.data').change(function() { // when dropbox value changes do this
getWeather(); // here I tried inserting table clearing code
});
});
function getWeather() {
$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) { // JSON request
$("#id").text(data.id); // changes fields accordingly
$("#city_id").text(data.city_id);
$("#temp").text(data.temperature);
$("#date").text(data.date);
});
}
</script>
Every item in dropdown menu does not have response from server, so I want it to clear the table just before making a new JSON request. So when JSON comes back with data, data is updated accordingly, but when JSON comes back with nothing, then all the tables will be empty.
At the moment when JSON retrieves no data, the old data still remains in the table.
I tried using $('.stuff').remove() and $('.stuff').clean() , but after using them right before getWeather(); then later I wasn't able to put info into table which I received from JSON. It just did not work anymore.
Feel free to ask any questions.
Try this
$('.stuff td').text("");
getWeather();
Depending how much of this sort of thing you will be doing on your site you might want to look into KnockoutJS, it is designed for dynamic displays with changing data, including auto hiding sections.

Categories

Resources