hide table header column - javascript

I use jquery code to pull results for a search query on my website. I would like to hide one of the table's column headers when the results appear. I have made the appropriate changes in HTML and the table appears correct when I go directly to the search results page, but if I refresh the search results page or pull a new query from that page, the table reverts back to the original text.
My question is, how do I adjust the jquery code to hide the column header text from appearing everytime it refreshes?
Here is the jquery I am using
jQuery('.loading').show();
var dataArr = {'region_id': region_id, 'from_date': from_date, 'to_date': to_date, 'course_no': course_no, 'course_id': course_id, 'gtr': gtr};
jQuery.ajax({
url: Drupal.settings.basePath + "course/search/region/api",
type: 'post',
cache: false,
datatype: 'json',
data: dataArr,
success: function (result) {
jQuery('.loading').hide();
var parsed = JSON.parse(result);
//jQuery('.result_search_region').html(result.data);
if (parsed.data.length > 0) {
jQuery('.result_search_region').html(' ');
jQuery('.result_search_region').append('<h5>Course Availability</h5>');
jQuery('.result_search_region').append(parsed.data);
} else {
jQuery('.result_search_region').html(jQuery('#dt_no_schedule').html());
}
}
});
Here is the html I am using:
<?php
$schedule_in_arr = Direction_Session::get('schedule_id');
$data_by_time = Direction_Session::get('data_by_time', array());
?>
<?php if (!empty($value['schedule_info'])): ?>
<table class="jz-table jz-table-bordered jz-table-striped">
<caption><?php echo $value['location_name']; ?></caption>
<?php if (!empty($value['schedule_info'])): ?>
<thead>
<tr>
<td>Start Date</td>
<td class="alncenter">Duration</td>
<td class="alncenter">Time</td>
class="alncenter"></td>
<td class="alncenter"></td>
</tr>
</thead>
<tbody>

It seems a little unclear do want to remove the head once you get the data (might be a poor user experience), or are you getting multiple headers shown?
To hide the thead figure out where/when you want to hide the header with this:
var elem = $("thead");
elem.css('visibility', 'hidden');
Or if you keep getting multiple:
table
thead
thead
...
Then I'd suggest the DOM node you're updating/replacing isn't correct. I'd suggest you look at replacing the tbody alone on update and get remove the thead in the html your graft in. One thing about the code, as someone that needs to test stuff alot, where are the ID's on your elements, make everyone's life easier.... :)

Related

How to remove clicked row while sending parametr to a function? Knockout

I have some complication with service removing. I have function that removes service on the server but I have to reload page to update table. I found way how to remove row by click-binding but there is the issue beacuse I can only remove row or get ID for delete service from server NOT both. :/
This is example of code that removes service on the server but doesn't remove table row.
HTML:
<table id="serviceView" class="fixed_header" border: 1>
<thead>
<tr>
<th>Name</th>
<th>Adress</th>
<th>Notification</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
<td data-bind="text: serviceId"></td>
<td ><button data-bind="click: $parent.DeleteService.bind(this, serviceId)">Remove</button></td>
</tr>
</tbody>
</table>
JS:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
self.DeleteService = function (serviceId) {
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
This is example of code that removes table row
When I use click-binding like this:
<button data-bind="click: $parent.DeleteService">Remove</button>
And change delete function to this:
self.DeleteService = function (serviceId) {
self.services.remove(serviceId)
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
// here I want to remove row but i doesnt goes here without service ID.
})
};
It removes row but instead serviceId I got [object, object] in the URL.
Can you help me with it ? I got idea to use jquery to just update the table but it's seems unnecessarily complicated for me when I can use knockout.
I know the solution is not that hard but I'am just unable to solve it..... -_-
I'am sorry for taking time with this bullshit but this is my first real project and I'am so desperate at this point beacuse I have lot of things to do and I'am stucked on this.
In your Js code, you can try this:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
var serviceIdRemoved;
self.DeleteService = function (serviceId) {
serviceIdRemoved = serviceId; // now you can do whatever you need more with this value
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
With this way of work you can user the content of the variable and donĀ“t loose it. Also if you get [Object, Object], you can:
console.log(serviceId) // to see the content in the console.
JSON.stringify(data) //to see the content in html
This source could help you to understand it better.
The [object, object] you are seeing is actually the data and event objects which are secretly added to the JS function parameters by Knockout. If you want to add your own parameter to the click binding then you should do it like this:
<button data-bind="click: function(data, event) { $parent.DeleteService(serviceId, data, event) }">Remove</button>
You can then define your JS function as follows:
self.DeleteService = function (serviceId, data, event) {
[code here...]
}
You can read up on the exact details of it in the excellent Knockout documentation here:
http://knockoutjs.com/documentation/click-binding.html
It's about half-way down under the heading that reads Note 2: Accessing the event object, or passing more parameters

Check if HTML table contains value or not in jquery

I have a table
<table id="orderTable">
<tr>
<th>Item Name</th>
<th>Price</th>
</tr>
And it is being filled in a loop when the page loads like this
<tr>
<td><?php echo $name ?></td>
<td><?php echo $price ?></td>
</tr>
I am trying to allow a user to add items to the table by clicking an add button next to the relevant item in a menu before this table using the following jquery:
$(".menu-body").on('click', '#add', function() {
add_to_table($(this));
});
I do not want the user to be able to add items to the table that are already in the table.
function add_to_table(selector)
{
var itemName = $(selector).closest(".item").find(".item-name").html();
var itemCost = $(selector).closest(".item").find(".item-price").html();
content = "<tr> <td>"+itemName+"</td> <td>"+itemCost+"</td>
var table = $("#orderTable");
if(!$('#orderTable tr > td:contains("'+itemName+'")').length)
{
// If table does not contain this itemName already.
table.append(content);
}
else {
//table has item
}
}
Currently, clicking the add button adds an item regardless of whether it is in the table or not, but then it correctly prevents a user from adding another one. So it works for items the user has added but it seems my conditional statement doesn't work for items that have already been put in the table by the PHP loop.
My desired behaviour is for the code to completely prevent a user from adding an item that is already in the table, but currently it only prevents them from adding items they have added themselves.

How to fetch data from file using ajax on clicking table rows

I am trying to fetch the data from files using Ajax by clicking row of table (passing row values to button on clicking rows) or by entering the variables in text box and pressing button. But it does not seem to be working.(Pls don't downvote as i am C++ programmer and learning web development.)
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<table bodrder=1 class='list'>
<thead>
<tr>
<th class='A'>ID</th>
<th class='B'>Value</th>
<th class='C'>Name</th>
<th class='D'>Cell #</th>
<th class='E'>Nickname</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>54235</td>
<td>Benjamin Lloyd</td>
<td>(801) 123-456</td>
<td>Ben</td>
</tr>
<tr>
<td>2</td>
<td>44235</td>
<td>XXXXXX</td>
<td>642363673</td>
<td>TRE</td>
</tr>
</tbody>
</table>
<div id="tabs" class="plots-tabs" style="padding-top: 10px; padding-bottom: 10px">
<table>
<tr><td>ID:<input id="id" type="text" class="inputbox" /></td></tr>
<tr><td>Value:<input id="value" type="text" class="inputbox" /></td></tr>
</table>
This is DIV element which will be filled by div element on clicking button or by clicking table row which also generate the event and click the button by passing values to ajax and fetchign data.
<p style="width: 100%; text-align: right;"><button type="button" id="button">Submit</button></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//here ID and value are parsed through table click event or from text box on clicking button
$.ajax({
url:filename,
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
},
success:function(result){
$("#tabs").html(result);
}});
var filename= "Data_"+ID+"_"+Value+".txt";
$("#tabs").load(filename);
});
});
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < 2; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
cat Data_2_54235.txt
Nice Work! Your code is working with first file.
cat Data_2_44235.txt
Nice Work! Your code is working with second file.
how can i implement the above code.
I see you generate a filename based on input values. That means that the ajax call will be made upon that filename, which is odd, becouse you have to create a file with that name.
Anyway, i don't see nowhere in your code that by clicking table rows you make an ajax call, you only save the innerHTML text to a variable data = [] and then alert it. But the problem is not here (if you don't expect to make ajax call when clicking table-rows), but it is inside the ajax call you are making when clicking the button.
first
url:filename
var filename= "Data_"+ID+"_"+Value+".txt";
I strongly suggest you don't do that. It will work if you make an ajax call to a php script which creates that txt file with filename name, and then make another ajax call to that file and fetch it.
second
data: {
ID: $("input#id").val(),
Value: $("input#value").val()
}
look here at data, the doc explains it. the code above means that to filename it will pass parameters (GET parameters, i.e. x?=...), but becouse your file is .txt, this doesn't make sense.
third
$("#tabs").load("demo_test.txt");
This will add the text inside demo_test.txt to $("#tabs") , like innerHTML does or .html() does. Do you have demo_test.txt on your host? i suppose this should work.
just change you ajax call and load call with this. this should work :
$("button").click(function() {
$.ajax({
url : "demo_test.txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
}
});
});
For clicking the table-rows, just add an event listener to table-rows, and make an ajax call. read the link i send you, as they are important to understand better what is ajax.
You can see no unnecessary data parameter is thrown to ajax call, and i put there an dataType, meaning that we expect text data to be recieved. If this doesn't work, you have to be sure that you are working on localhost server(for ajax to work...) and you have demo_test.txt , and the url is passed correctly
example using input values to fetch from ajax:
$("button").click(function() {
var id = $("input#id").val();
var value = $("input#value").val();
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});
example of event handler click <tr>
$("table tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the clicked tr (this is the ID i suppose)
var value = $(this).find("td")[1].text(); // gets the second td of the clicked tr (this is the VALUE i suppose)
$.ajax({
url : "Data_" + id + "_" + value + ".txt",
dataType: "text",
success : function (data) {
$("#tabs").html(data);
},
error: function (data) {
#("#tabs").html('No such file found on server');
}
});
});

How to edit table contents from another page using javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm looking to add a page to my website that will have a table that will display the products that are available.
What I would like to be able to do, is make it so that the contents of the table can be changed from another page (say an admin page). Is it possible to do something like this using JavaScript or something similar? If so can you please point me in the right direction.
Much appreciated thanks.
There are few ways.
Not involving server-side
You need a reference to the other window. You can get that e.g. by opening the window - window.open().
Then you use the HTML DOM methods, e.g. the document.getElementById(...) and then the specific element's API:
https://developer.mozilla.org/en/docs/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
http://www.w3schools.com/jsref/dom_obj_table.asp
Involving server-side
This means that one page would send some data to the server and the other would read them.
You can use the AJAX concept for that - see the answer with XMLHttpRequest.
The other page would have to check periodically, or the first page would have to give it some signal - call some JavaScript method you wrote, or reload the window. Other option would be to use the push concept, but that's currently an advanced technique.
You could use XMLHttpRequest for this , but I would recommend that you use jQuery which would then be the $.ajax() function. What this does is send data to the server without refreshing the page or without anybody knowing about it really.
So what you could do is on the admin side is send some changes data to the server and on the client side unless you use a Web Socket you would have to contact the server every so many seconds to see if there are any changes. then the server would send you any changes that would have been made by the admin then you would work with that result with javascript to display changes on the web page.
What is Ajax
jQuery Ajax
Here is the requested example using jQuery
in your php you would have something like this
if($_POST['type'] === 'updateProduct') {
// update database with new price
// You could have a field in the database that now say's
// that the product has been updated
// send the response
echo 'done';
}
// And the admin ajax something like this
$.ajax({
type: 'POST',
url: 'linkToYourFile.php', // The php file that will process the request
data: {
type: 'updateProduct', // This is all the data you wan't to send to your php file
productID: 8484737,
newPrice: '$100.99'
},
success: function( result ) { // if we get a response
if(result === 'done') {
// The product has been updated from the admin side
}
}
});
// on the client side
if($_POST['type'] === 'checkForUpdates') {
// Contact the database and check that $_POST['productID']
// has been updated
// use php's json_encode function to echo the result
}
var checkForUpdates = function() {
$.ajax({
type: 'POST',
url: 'LinkToYourFile.php',
dataType: 'JSON',
data: {
type: 'checkForUpdates',
productId: 8484737
},
sucess: function ( result ) {
if( result.updated === true ) {
someElementPrice.textContent = result.newPrice;
}
}
});
};
window.setInterval(checkForUpdates, 3000); // Send's the update request every 3 seconds
Note - it's not easy to do this stuff if your not familiar with it. but you will learn.
Thats the fun part. and there is a lot more to it behind the scenes, but this is the idea of it
Possible solution
Using an AJAX call, you could store the table itself in an HTML file.
Here is an example page. If you have any questions, do not hesitate to ask them. I added a few functions such as Add Row.
LIVE DEMO
Admin management page (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery AJAX</title>
<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style rel="stylesheet" type="text/css">
tr, td,th{
border-collapse: collapse;
border:1px solid;
}
td{
height:22px;
min-width:125px;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">"http://jquery.com"</script>
<script type="text/javascript">
/* ---------------------------------- */
/* See the SCRIPT part of this answer */
/* ---------------------------------- */
</script>
</head>
<body>
<h1>jQuery AJAX Table</h1>
<section>
<article>
<div id="myTable" contenteditable></div>
<nav data-type="table-tools">
<ul>
<li>
New row
</li>
<li>
New column
</li>
<li>
Save table
</li>
</ul>
</nav>
</article>
</section>
</body>
</html>
SCRIPT
/* On page load */
$(document).ready(function () {
var getTable = function () {
/*We empty the div */
$('#myTable').html('');
/*We load the table */
$.get('myTable.html', function (callback_data) {
var table = callback_data;
document.getElementById('myTable').innerHTML = table;
});
};
getTable();
/* ----- */
/* New row button */
$('#addRow').click(function (event) {
/* Prevents the real anchor click event (going to href link)*/
event.preventDefault();
/* We get the number of columns in a row*/
var colNumber = $($('#myTable tbody tr')[0]).children('td').length;
var tr = document.createElement('tr');
var td = "";
for (var i = 0; i < colNumber; i++) {
td = document.createElement('td');
td.appendChild(document.createTextNode("\n"));
tr.appendChild(td);
}
$('#myTable tbody').append(tr);
});
$('#addColumn').click(function (event) {
event.preventDefault();
$.each($('#myTable table thead tr'), function () {
$(this).append('<th></th>');
})
$.each($('#myTable table tbody tr'), function () {
$(this).append('<td></td>');
});
});
$('#saveTable').click(function (event) {
event.preventDefault();
var table = $('#myTable').html();
$.post('saveTable.php', {
'myTable': table
}, function (callback_data) {
console.log(callback_data);
$('#myTable').slideToggle('fast');
setTimeout(function () {
getTable();
$('#myTable').slideToggle();
}, 100);
});
});
});
saveTable.php
<?php
if(!isset($_POST['myTable']))
die('No data provided.');
$table = $_POST['myTable'];
$handle = fopen('myTable.html','w');
$result = fwrite($handle,$table);
if($result)
fclose($handle);
else
die('Error writing file');
?>
myTable.html
<table>
<thead>
<tr>
<th>Lorem ipsum dolor.</th>
<th>Velit, vero, quis.</th>
<th>Id, dolore, commodi!</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem ipsum.</td>
<td>Voluptatibus, maiores.</td>
<td>Quod, et.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ex, assumenda!</td>
<td>Qui, pariatur!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Alias, amet.</td>
<td>Delectus, itaque!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Praesentium, quod.</td>
<td>Dolor, praesentium?</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Beatae, perferendis!</td>
<td>Voluptates, earum!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Ratione, quis.</td>
<td>Cupiditate, repellendus.</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Porro, labore.</td>
<td>Eligendi, nemo!</td>
</tr>
<tr>
<td>Lorem ipsum.</td>
<td>Soluta, suscipit.</td>
<td>Dolorem, dolores.</td>
</tr>
</tbody>
</table>
This is possible with some limitations:
You should change the table that displays the products, to fetch the values beeing displayed using ajax. Then you have 2 possibilities: (I'm pretty sure there are more but I only think of those 2 at the moment)
create a timer which will fetch the values for a product every X seconds
create a listener that will be called when a value in the db gets updated
This way you can change the values in an backend and the will be automatically updated in your frontend view.
You can have a look at the meteor framework where they use 'Live HTML' excessive.

Dynamic table column update by id, done right?

I am kinda new to Ajax/Json so I would like to know if the following is at least near to the best practice. The goal is to update specific columns (in this case quantity and price) of a table every x seconds.
I got a HTML table defined like this:
<table id="#edition_table>
<tbody>
<tr>
<td class="name">Lightning Bolt</td>
[...]
<td class="qty">2</td>
<td class="price">$4.99</td>
<tr>
<tr>
<td class="name">Fireball</td>
[...]
<td class="qty">0</td>
<td class="price">$0.07</td>
<tr>
[...]
</tbody>
</table>
And a JS function defined like this:
function edition_update(edition)
{
var table_rows = $('#edition_table').find('tbody tr td.name a');
$.ajax({
type: 'GET', url: 'ajax_edition_update.php', data: { edition : edition }, dataType: 'json',
success: function(json_rows)
{
var new_qty, new_price;
table_rows.each(function(index) {
var td_id = $(this).attr('href').replace('?card=', '');
for (i in json_rows) {
if (json_rows[i].card_id == td_id)
{
new_qty = json_rows[i].qty;
new_price = json_rows[i].low_price;
break;
}
}
var parent_tr = $(this).parent().parent();
parent_tr.find('td.qty').text(new_qty);
parent_tr.find('td.price').text(!isNaN(new_price) ? '$' + new_price : new_price);
});
}
});
setTimeout(edition_update, 30000, edition);
}
The PHP file returns a JSON including card_id, qty and low_price.
This does work fine. I guess I could set up a data-id=[card_id] on the class=name td to get rid of the .replace, but that kinda blows up the html footprint as the id is already present.
The real question is whether any performance improvements (especially regarding the two loops) are possible or necessary? The target number of rows per table is arround 500 and the content and order is totally dynamic/unpredictable, of course.

Categories