Now I am implementing the editUser() function. I create function to handle click button
$( "#table-list tbody" ).on( "click", ".btn-edit", function() {
operation = "E";
for (var i in tableStore) {
var temp = JSON.parse(tableStore[i])
if ($(this).attr("data-id") === temp.id) {
$enterID.val(temp.id);
$enterFirstName.val(temp.firstname);
$enterLastName.val(temp.lastname);
$enterLPhone.val(temp.phone);
$enterEmail.val(temp.email);
$enterAddress.val(temp.address);
$enterBirthday.val(temp.birthday);
$enterGender.val(temp.gender);
$enterID.attr("readonly", "readonly");
$enterFirstName.focus();
}
}
});
this help me retrieve data from local storage. Then when I change some information on the input tag I wan to the data will updated into local storage. This is function help me do that:
function editUser(tableStore, user) {
tableStore[tableStore] = user
operation = "A"
}
and when the form is submit I handle it like that:
$( "#table-list tbody" ).on( "click", ".btn-delete", function() {
selected_index = parseInt($(this).attr("data-id").replace("Delete", ""));
$(this).parents('tr').remove()
deleteUserInfor();
});
$(".form-information").on("click", ".btn-save-change", function () {
if (operation == "A"){
var newUser = readUserFromDOM();
addUser(tableStore, newUser.serialize());
localStorage.setItem("tableStore", JSON.stringify(tableStore));
}
else {
var editingUser = readUserFromDOM();
editUser(tableStore, editingUser.serialize());
localStorage.setItem("tableStore", JSON.stringify(tableStore));
}
});
But some thing is wrong and I can't save the data. So can you help me show what is wrong is there.
This my code user manager code pen.
Beside that, the operation is not good idea for the pure function in js. If you can please help me to refactor it
Many thank for your help
Final Update:
https://codepen.io/vikrant24/pen/ybgPww
As shown in below function:
You need to specify tableStore[i] value of i. Because i is the row number. If you are editing row 5th of grid then update tableStore[4]=user likewise if you are updating 3rd row then update tableStore[2]=user. I have added the code for it. I hope you understood.
function editUser(tableStore, user,i) {
tableStore[i] = user
operation = "A"
}
You should use this instead because eventually you would need to update that tableStore in localStorage:
function editUser(tableStore, user,i) {
tableStore[i] = user;
localStorage.setItem("tableStore", JSON.stringify(tableStore));
operation = "A";
}
Previous Answer:
Use this function It will work:
function editUser(tableStore, user) {
tableStore[0] = user
operation = "A"
}
You should use this instead because eventually you would need to update that tableStore in localStorage:
function editUser(tableStore, user) {
tableStore[0] = user;
localStorage.setItem("tableStore", JSON.stringify(tableStore));
operation = "A";
}
Related
I'm having trouble changing the class after making a jquery get request.
code:
<script>
//global variable
var table = []
var numberofaccounts = 0
$(document).ready(function() {
$('#form1').validate();
// add numbers to select ids
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
$('#apply_btn').click(function() {
table = []
var count = 0;
var text = "";
var tracker = 0
$('#stats_table tr').each(function(){
count = 0;
text = "";
$(this).find('td').each(function(){
count++;
if (count == 4) {
text += $( ".select_class"+ tracker + " option:selected" ).val();
} else {
text += " " + $(this).text() + " ";
}
})
table.push(text);
tracker++;
});
$.post("/apply_changes", {"data": JSON.stringify(table)}, function(data) {
var res = JSON.parse(data);
if (res.data == true){
$('#updated').text("Update Successful").css('color', 'green');
$.get("/", function( data ) {
$('#stats_table').load("/ #stats_table");
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
} else {
$('#updated').text("Update Unsuccessful").css('color', 'red');
}
});
});
});
</script>
So when the page first loads this method changes the class on dynamically created select elements.
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
After I make a post to flask the if the response data is true I go ahead and make a get request to grab the updated items from the db. I then refresh the table. This works great if I make one request. However on the second post nothing happens. This is because the classes that I modified at the start of the page load no longer exist. So i added the method above to also trigger after the get response (I also tried at the end of the post response). The problem is that the method doesn't seem to run again. The classes aren't there and as a result when I go to make another post request it can't find the element. How do I go about fixing this?
Things to note: The get request is necessary, the ids and classes cannot be statically assigned.
You are trying to assign classes before you even refresh your table.
$('#stats_table').load("/ #stats_table"); is called asynchronously and returns before it even completes.
You need to put you code, for assigning classes, inside the complete callback of your .load() call:
$('#stats_table').load("/ #stats_table", function() {
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
this is similar to a previous post where I wanted to sync my data source when the user changes rows in the grid (exactly as Access saves out a record)
In the post above am am shown how to do this when the user tabs into a new cell as follows...
function refreshFix1() {
kendo.ui.Grid.fn.refresh = (function (refresh) {
return function (e) {
this._refreshing = true;
refresh.call(this, e);
this._refreshing = false;
}
})(kendo.ui.Grid.fn.refresh);
kendo.ui.Grid.fn.current = (function (current) {
return function (element) {
// assuming element is td element, i.e. cell selection
if (!this._refreshing && element) {
this._lastFocusedCellIndex = $(element).index();
this._lastFocusedUid = $(element).closest("tr").data("uid");
// Added this For navigation mode
this._lastNavigationCell = this.tbody.find("tr:last td:last");
}
return current.call(this, element);
}
})(kendo.ui.Grid.fn.current);
kendo.ui.Grid.fn.refocusLastEditedCell = function () {
if (this._lastFocusedUid) {
var row = $(this.tbody).find("tr[data-uid='" + this._lastFocusedUid + "']");
var cell = $(row).children().eq(this._lastFocusedCellIndex);
this.editCell(cell);
}
};
The above gives us a function we can call (refocusLastEditedCell) after we sync the data source, and seems to work great.
I now want to do the same for when the grid is in Navigation mode. Following the above example, and the doco here , I added the following...
// Call this to go back to a cell in *navigation* mode
kendo.ui.Grid.fn.refocusLastNavigatedCell = function () {
var self = this;
if (this._lastNavigationCell) {
// try see if calling "async" using setTimeout will help
setTimeout (function(){
console.log("going back to navigation cell");
self.current(this._lastNavigationCell);
self.table.focus();
}, 10)
}
};
I then have the following code to call sync on the datasource...
vm.gridData.sync();
if (vm.editMode){
/ Go back to edit cell
grid.refocusLastEditedCell()
} else{
// Go back to navigation cell
grid.refocusLastNavigatedCell();
};
}
(full example here)
Unfortunately I do not seem to be going back to the same cell, it again just jumps to the top left cell.
Any ideas how to get it to work in this situation would be greatly appreciated.
Thanks in advance for any help!
You need to use the row uid and cell index as done in the original code; the <td> element you're trying to focus doesn't exist anymore once the grid gets rerendered. So you could do this:
kendo.ui.Grid.fn.current = (function (current) {
return function (element) {
// assuming element is td element, i.e. cell selection
if (!this._refreshing && element) {
this._lastFocusedCellIndex = $(element).index();
this._lastFocusedUid = $(element).closest("tr").data("uid");
// For navigation mode
var cell = current.call(this, element);
this._lastNavigationCellIndex = $(cell).index();
this._lastNavigationCellUid = $(cell).closest("tr").data("uid");
}
return current.call(this, element);
}
})(kendo.ui.Grid.fn.current);
and use it:
kendo.ui.Grid.fn.refocusLastNavigatedCell = function () {
if (this._lastNavigationCellUid) {
var row = $(this.tbody).find("tr[data-uid='" +
this._lastNavigationCellUid + "']");
var cell = $(row).children().eq(this._lastNavigationCellIndex);
this.current(cell);
}
};
You've got so many customizations now, you may want to extend the grid itself instead of replacing its methods one by one.
By the way, you could probably integrate all of this in the refresh method, so you don't have to explicitly call it:
kendo.ui.Grid.fn.refresh = (function (refresh) {
return function (e) {
this._refreshing = true;
refresh.call(this, e);
this._refreshing = false;
if (!this.options.editable) {
this.refocusLastNavigatedCell();
} else {
this.refocusLastEditedCell()
}
}
})(kendo.ui.Grid.fn.refresh);
I didn't understand why you want to refocus
this.tbody.find("tr:last td:last");
so I changed it for the (demo).
I need to process an AJAX request twice, first, when the site has been opened first time, and second, when a button is clicked. I dont want to write 2 similar functions. So I created an ajaxPost function. I wonder how to detect what event has called the ajaxPost function? opening the browser or clicking a button?
function ajaxPost() {
url = "post.php";
if (this!=Window) {
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
Check for the jQuery event that you're passing with a click.
function ajaxPost(event) {
url = "post.php";
if (event == undefined || event == null) { //Was not generated by a user click
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
A simple solution would be to include an additional parameter when calling the function:
function ajaxPost( caller ) {
switch( caller ){
case "initial_load":
// called on page load
break;
case "button_click":
// called on button click
break;
}
...
}
Now you would need to pass this parameter from the two different types of calls:
$(document).ready(function() {
ajaxPost( "initial_load" );
$("input[type=button]").on( "click", function(){
ajaxPost( "button_click" );
});
});
Following is my function which I am using to load data as per < last id of li .post-list but still I am getting repetition of same ids that were pulled before. Kindly let me know how can I resolve this issue so the old ids doesn't load/repeat itself again.:
function loadData()
{
$('div.postloader').html('<img src="img/loader.gif">');
$.post("getData.php?lastID=" + $(".post-list:last").attr("id"),
function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
});
};
A possible soution to prevent this is to store the last ID in a global variable in JS and increment that, so you don't have to rely on selecting the right element to find the ID to POST.
you're pulling the data from the server too fast, try adding a flag that will prevent pulling the items while the request is running:
var flagPulling = false;
function loadData() {
if( flagPulling ) {
return;
}
flagPulling = true;
$('div.postloader').html('<img src="http://www.zesteve.com/img/loader.gif">');
$.post("/getData.php?lastID=" + $(".post-list:last").attr("id"), function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
flagPulling = false;
});
};
Just started with knockout and need to implement page change warning. Following is the code snippet. I just need an alert pop up as warning if any change is made on the page.
function parseViewModel() {
var viewModel = JSON.parse(getState());
viewModel.checking = ko.observable(false);
viewModel.Slider = new ko.observable(100 - viewModel.Slider);
viewModel.CausalsList = buildHierarchy(viewModel.Causals);
viewModel.Causals["-1"] = "Total Marketing Budget";
viewModel.GeographiesList = ko.observableArray(gl);
viewModel.Geographies["0"] = "All Geographies";
viewModel.ProductsList = ko.observableArray(pl);
viewModel.Products["0"] = "All Products";
.
.
.
return viewModel;
}
function bindModel() {
model = parseViewModel();
ko.dirtyFlag = function (root, isInitiallyDirty) {
var result = function () { },
_initialState = ko.observable(ko.toJSON(root)),
_isInitiallyDirty = ko.observable(isInitiallyDirty);
result.isDirty = ko.computed(function () {
return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
});
result.reset = function () {
_initialState(ko.toJSON(root));
_isInitiallyDirty(false);
};
return result;
};
model.dirtyFlag = new ko.dirtyFlag(model);
model.isDirty.subscribe(function () {
alert("Page change warning!");
});
ko.applyBindings(model, $('#const').get(0));
ko.applyBindings(model, $('#buttonDiv').get(0));
}
Referred Ryan Niemeyer's blog. Unfortunately, it's not working anymore. Any insights please?
You would want to subscribe to model.dirtyFlag.isDirty in your case rather than model.isDirty.
One way to do is by using customBinding. I'm not that familiar with KO either but this might be something you're interested on.
Basically you would do is :-
ko.bindingHandlers.myFunction = {
update : function(){
//do something
}
}
http://knockoutjs.com/documentation/custom-bindings.html
And call it on your element using :-
<h1 data-bind="myFunction:{}"></h1>
Also, a jsfiddle to show how it works. (If you change the value of the First Name and focus out of it then the customBinding gets triggered. )
http://jsfiddle.net/3vuTk
Not sure if it's the best practice though.