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.
Related
I have an html table with id:#mytable in my asp.net-4.5 webpage, which is created in the c# site and sending to the aspx. In this Html table, at the end of each row there is a DELETE button like below:
...
html.Append("<td><input type=\"button\" runat=\"server\" value=\"Delete\" onclick=\"deleteRow(this)\" /></td>");
When this button is clicked, deleteRow(this) function is triggered with the code below:
btn.parentNode.parentNode.parentNode.removeChild(row);
When this line above runs, the regarding row is being immediately deleted and I do not see the row in the screen anymore.
This html table is represented as a datatable (javascript) like below:
$('#myTable').on('error.dt', function (e, settings, techNote, message) {
console.log('An error has been reported by DataTables: ', message);
}).DataTable({ fixedColumns: true,
"columnDefs": [{
"width": '60%',
"defaultContent": "-",
"targets": "_all"
}]
});;
This is also working well, my html table turns into a datatable. My problem is, after I delete a row from the table, if I change the sorting, or entry limit per page (10 by default) etc., I start to see the row I have just removed on the page, inside the table. It seems like my deleteRow function deletes the row not permanently. How can I fix this issue? Any help will be so appreciated.
EDIT: I needed to refresh the page after delete button click with JS: document.location.reload(true) and page_load re-reads the data, to fix the issue. Thanks #NTR and #J E Carter II
EDIT2: Using $('#myTable').DataTable().rows(row).remove().draw(false); while removing the row fixed the issue without the need of re-read data from DB. Check my answer.
As #NTR and #J E Carter II stated, re-reading the data solves the issue perfectly. However my main purpose here is not to re-read the data from the DB, I was looking for a solution providing that and found something. All I did is to change the row btn.parentNode.parentNode.parentNode.removeChild(row); into $('#myTable').DataTable().rows(row).remove().draw(false); and it works perfectly, after the table is refreshed the removed data is not seen on the screen. Here is the complete ajax function:
var row = btn.parentNode.parentNode;
$.ajax({
type: 'POST',
url: 'DataManagementPage.aspx/DeleteRowFromMyDatabase',
data: JSON.stringify({ id: id, grId:grID, city: city }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg)
{
$('#myTable').DataTable().rows(row).remove().draw(false);
}
});
The topic #NTR provided also offers a solution in server side: Deleting specific rows from DataTable
EDIT: Please note that DeleteRowFromMyDatabase returns true after the removal in DB.
Javascript is a client side technology it does not have the ability to communicate with a database. Your table is generated from the database with your server side .NET code. To accomplish what you want, you need to also delete the row in your database. To communicate with your server side code, you can use AJAX : AJAX introduction. AJAX is a big subject, you might have to do additional research.
So, in your deleteRow function you will have to delete the row client side like you are doing now and then, using ajax, delete the row server side.
Hope it helps !
You will have to reinitialize the data table with a fresh ajax call or mutated object. Your removal code is only taking out the rendered row, not the data that drives it, so when you call a redraw with sort, it is correctly rendering the state of the model, regardless of what mutations have occurred in the DOM.
I know you say you don't want to reread the data, but that is the correct thing to do. The remote data is the source of truth for your rendered datatable.
I have this html data-table where each table cell is editable. I can edit the cell value and it is saved temporary. But when I update the page it is lost. So I tried to save the html instance in excel file so that I can see the updated cell in future.
Below function shows me the edited value in console
$(document).ready(function() {
var table = $('#example').DataTable();
table.MakeCellsEditable({
"onUpdate": myCallbackFunction
});
function myCallbackFunction(updatedCell, updatedRow, oldValue) {
console.log("The new value for the cell is: " + updatedCell.data());
console.log("The old value for that cell was: " + oldValue);
console.log("The values for each cell in that row are: " + updatedRow.data());
updatedCell.data();
updatedRow.data();
table.draw();
}
});
And This is my Ajax for calling python function:
$("#sa").click(function() {
$.ajax({
url: '/save',
type: 'POST',
success: function(response) {
alert('ok')
}
})
});
And Basically my python function takes a takes the source code of page and save it in excel. But the thing is my table is getting edited but the script is saving the old values. When I it using chromes inspect element I can see the updates value but when I see it using View page source I see the old values.
Can anybody tell how can I take the updated html page source and send it using ajax
The main difference between page sourceand inspect element is:
Page Source shows what server initially responded, that is the actual sent HTML from the server.
Inspect Element is showing the current state of the DOM after JS manipulation.
DOM is generated using the entire initial page's source/HTML.
That's why your page source will always be the same.
What you can do is post the html content of document in your ajax to get the latest page source.
The following should help you in getting updated DOM source as string:
document.documentElement.innerHTML
Though not sure why you need to post source as you can only post updated values and update database accordingly.
Look into DataTables State saving, it's an option in the plugin [stateSave: true] which uses localstorage and sessionStorage to retain the state of your table.
Example:
$(document).ready(function() {
$('#example').DataTable( {
stateSave: true
} );
} );
Since the state is saved, you can simply retrieve the data everytime you reload the page.
I am trying to convert a normal field to autocomplete and making a ajax call to get the data in JSON and then set it to that autocomplete.
I do not know much on JQUERY, I spent around 5-6 hours just to know I have to initialize before using any function on the auto complete field.
What I have done so far
I managed to initialize and convert my text field to autocomplete and checked that using the inspect option it shows autocomplete , and also am able to make the ajax call which is pulling the data verified that using f12 network option.But it does not show up as a type ahead in my autocomplete option.
HTML
<div id ="myName">
<table class="some_class">
<tbody>
<tr>
<td >
<label>NAMES</label>
</td>
</tr>
<tr>
<td >
<input type="text" id="nameText" />
</td>
</tr>
</tbody>
</table>
</div>
initialization part
myName.on('valueChange',function (value){
$("#nameText").autocomplete({
appendTo:"#nameText",
source:function(event,ui){
var name=myName.value();
$.ajax({
url: "www.getmeSomeData.com/query/name:"+name,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
}
});
},minLength:1});
});
$("#nameText").focus(function(even,ui){
$((this).data("uiAutocomplete").search$(this).val());
});
PROBLEM
1.The autocomplete does not show any result even though from ajax call i see json data coming.
2.The value change starts only after i type abc and then move the cursor somewhere else and then click it back,before that nothing invokes.Where as what is expected is as soon as I type a or ab or abc it should make ajax call and pull the data show in autocomplete dropdown.
Can someone please help? I did not come here without researched but I think i tried a lot of things and nothing worked so am totally confused.Kindly help me, i have spent around 2 days on this.
Thanks in advance.
I finally figured out what was the problem in my code.I actually was not able to add option to my input autocomplete.To make it work I needed to update my html with
HTML
just replace <input class="nameClass" type="text" id="nameText" />
And the jquery part needed updates, the above was just a very novice attempt.
1. I should have used $.each($(".nameClass"), function(index, item) {
2. and then $(item).autocomplete
3. Also in source should have used source:function(request,response)
4. In the ajax call request.term (which will take whatever you input in the autocomplete field where as my method was invoking the ajax call only after tab out.
5. Map the data of response response($.map(data.data, function(item){
6. Write a select callback function to make anything happen after i click on any entry in the typeahead
7.data("ui-autocomplete")._renderItem = function (ul, item) { >To show the data in a formatted way after the ajax call.
INITIALIZATION
$.each($(".nameClass"), function(index, item) {
$(item).autocomplete({
source:function(request,response){
$.ajax({
url: "www.getmeSomeData.com/query/name:"+request.term,
type:"GET".
dataType:"json",
success:function(result){
//set this result in autocomplete which I am not sure how to do
response($.map(data.data, function(item){
return{
value:item.somethigncomingfromJson //will set into the field
data:item
}}))}}
});
} ,minLength :2,
select:function(event,ui){
//do something on select of a row in the autocomplete dropdown
}}).data("ui-autocomplete")._renderItem=function(ul,item){
return $("format in which you want to see the data").appendTo(ul);
});
}
No other event is required.
I keep track of my comic book collection online using a mass amount of tables.
I color the table cells based on which ones I have vs. don't have.
I'm trying to make my life easier by adding some jQuery to my site that will allow me to simply "click" on the cell to change the color.
What I don't know how to do is make the change PERMANENT. It works fine an dandy (and I'm going to add more functionality to cycle through more colors), but when I refresh the page all the changes made to the page are lost.
Is there a way to make the changes permanent?? Adding a "save" button perhaps? Not sure how to achieve this.
Simple Example of what I'm doing:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('td').click(function() {
$(this).css('background-color', '#5f0');
});
});
</script>
<table>
<tr>
<td>#1</td>
<td>Comic Title</td>
<td>Collected Edition</td>
<td>Omnibus</td>
</tr>
</table>
You can do that using localstorage or server side storage.
When the user makes changes to the page, store the css properties with respect to an identifier for that field preferrably ID. In JSON format and stringify it before storing to the localstorage.
When the page refreshes or loads, In the onload event , check the localstorage if it has any data. If it's not null then retrieve the value using the key. let's say "personalization". Then use JSON.parse() to get the original JSON object.
Now loop through the json object and use the key as ID and the value as the css properties. To apply the changes.
Example:
var cssprop = { 'cellId' : { 'color': 'red'}}
If the above is the json you have constructed on click of the cells.
localStorage.setItem("personalize", JSON.stringify(cssprop));
now on window.onload()
$(function() {
// In case you are persisting data in the server, make ajax call to retrieve the data and then store it in localstorage.
if(localStorage.getItem("personalization") != null) {
var personalize= localStorage.getItem("personalization");
var cssprop = JSON.parse(personalize);
// you can iterage the object
// use $("#"+keyOfObject).css(// use value of object);
}
});
I am using this code to edit data on table ,this is allowing me to edit data ,but I am not able to find that where and how should I store data locally on that form itself ,if i don't want to store it in database, I want to know what this "/somewhere" should be(url or some file or what).
<table id="mylist_remark"><tr>
<td class="editable" contenteditable="true">Something</td>
</tr></table>
$("#mylist_remark .editable").bind("blur", function(e) {
console.log($(e.target).text());
$.post("/somewhere", {remark: $(e.target).text(), candidate_id: $(e.target).nearest("tr").attr("id")}, function() { console.log("success"); });
});
... how should I store data locally on that form itself ,if i don't want to store it in database...
One solution would be to use localStorage to save the form elements locally.
If you felt like using jQuery, you could make the problem simple:
$("input").change(function(){
var input = $(this).val();
localStorage.setItem("input",input);
}
Then when the page loads, you set the val to the localStorage item:
var input = localStorage.getItem("input");
$("input").val(input)
More on localStorage, and even more on localStorage.