javascript some button clicks dont refresh page? - javascript

Alright so I got two buttons, one adds a dog to the doglist and another one clears the whole list.
Both work fine, just one thing that's bothering me is that only the OnSubmit button refreshes page.
The dog list is loaded in OnReady, and the list only gets refreshed when an item is added. When I clear the list I need to manually refresh the page to see changes.
function OnSubmit(event) {
addToStorageList(dogs, dog);
}
function OnClickClearList() {
localStorage.setItem('dogs', JSON.stringify([]));
}
function addToStorageList(listName, itemToAdd) {
var list = JSON.parse(localStorage.getItem(listName));
if (!Array.isArray(list)) {
list = [];
}
list.push(itemToAdd);
localStorage.setItem(listName, JSON.stringify(list));
}
$('#btn1').click(OnSubmit);
$('#btn2').click(OnClickClearList);
I appreciate any help, thanks!

In my opinion noone of them should refresh, to refresh you should use
"location.reload(); "
in the end of your functions
the reason one of them refreshes is either in code I cannot see (that you havn't posted) or that one is called OnSubmit and that is interfering with form submit buttons or something

Related

Click back button twice to go back in history

I have a single page application and would like to navigate through the history using browser back and forward button. I am facing an issue when i click the back button once it does not navigate to the previous page but stays on the current page. Then when i click the browser back again it takes me to the previous page. I have tried out the following.
class PageModule {
constructor() {
window.addEventListener("popstate",function(){
this.handleHistory(true);
}.bind(this),false);
}
handleHistory(popStateEventFired = false){
if(popStateEventFired){
history.replaceState();
}else{
history.pushState(null,null);
}
history.pushState(null,null);
}
When i issue a search i add the search param as a query param in the url ?question=testsearch and call the method handleHistory(). I have checked other answers to similar problem but they dont seem to help.
I have to do this using vanilla javascript or knockoutjs as we maintain HTML bindings using knockoutjs but am not able to achieve this properly.
Any help is appreciated

Empty value when opening one modal after another

I am making a web application with Django, JavaScript, JQuery, and ajax. I've been with this problem for two days, and I can't make progress at all, the problem is the following:
I have two modals, in which a form is loaded. If I hit the create button to open the create modal, everything works fine, I can fill in the form, it is submitted and the data is saved to the database. If I give the edit button, the modal is loaded with the form with the data of the object that is being edited, and everything works perfectly. The problem is when I first open the creation modal, close it, and open the edit modal, a very strange thing happens, and that is that the value of an input that I need always returns it to me empty, despite not being empty. Here is the code (what matters, a summary):
<script>
$(document).ready(function () {
$('#edicion').on('shown.bs.modal', function (e) {
let $tipoActivo = $('#id_tipo_activo');
console.log($tipoActivo.val());
});
$('#creacion').on('shown.bs.modal', function (e) {
let $tipoActivo = $('#id_tipo_activo');
console.log($tipoActivo.val());
});
});
</script>
If I open the create modal first, close it, and then open the edit modal, let $TipoActivo = $('# id_tipo_activo'); it always empty (''), when in reality I see that its value is not empty.

jQuery Form won't hide and function return undefined

I'm having a problem with one the buttons. It doens't work properly.
When I click "Add Run" button and then "Home" button almost nothing work. The form that is dynamically created doesn't hide and search input doesn't show, and function return undefined.
$("#home").on("click", function () {
$("#search").show();
$("#addForm").hide();
$("#noPrevious").hide();
complete()
console.log(complete())
});
But on the other hand, some things work, they hide or show. For example, after refresh, when I click "All my Runs" it displays text, which will hide after clicking on "Home" button, and on top of that, search input field shows up. I don't understand this. Does anybody know what's wrong?
Thanks in advance.
Here is CodePen and GitHub. The problem is at the top of .js file.
https://codepen.io/ovy1448/pen/gZrKOX
https://github.com/ovy1448/MyRun/blob/master/js/main.js
Your problem is that you are not initializing your values properly. For example, in the case of bookmarks your code presumes that localStorage has a value with that key. However, that is not necessarily the case. You would need to have a default value for bookmarks. A helper function could be useful here:
function getBookmarks() {
var bookmarks = localStorage.getItem("bookmarks");
if (!bookmarks) bookmarks = [];
return bookmarks;
}
and then replace all occurrences of localStorage.getItem("bookmarks") to getBookMarks() in your code, except the one in the function above. Pay attention to other initializations as well.
EDIT
If you want to parse JSON inside the function, you can do it like so:
function getBookmarks() {
var bookmarks = localStorage.getItem("bookmarks");
if (!bookmarks) return [];
return JSON.parse(bookmarks);
}

javascript property race condition

I have a phonegap project on iPhone and Android. The issue appears to be a race condition on the surface, but I don't understand how it happens. Users are able to click on a button which has a closure callback that sets a property of an object, and then clears the screen and loads the main menu. In code:
button.onclick = function (employee) {
return function () {
employee.task = "some task";
returnToMenu();
}
}(employees[i]);
After the user is back on the main menu, they can click on a button that loads a screen which displays all the users. If an employee has that task property set, additionally formatting should be done to the button for that employee.
if (employee.task)
// style the button being created for this employee
Somehow, if one clicks fast enough, the formatting is not done. If you click back (to the main menu), and reload the screen, the formatting is now done. Given the code above, I do not see how employee.task could possibly return undefined after the menu has been loaded. What's going on here?

How to modify jQuery mobile history Back Button behavior

I'll start this off with I have researched a bit, but no solution that solves what seems like it should be a simple JQM modification.
I have a wine review webapp that has the following view user flow:
http://5buckchuck.com/
Wine type > Wine list > Wine Details > Wine review (redirect via django backto ) > Wine Details updated from review
What I want to happen is when the user presses the back button it should go back to the wine list. What currently happens is the the Wine Detail view is reloaded. It takes pressing back three times to get back to the Wine List. :-(
My thoughts to solve this were two:
Splice the last 3 items from the history stack, if the last items in the history stack was Wine Review. I had a hard time trying to introspect the last history object to get the pageURL. I have a feeling that this solution is a bit too fragile though.
var last_hist = $.mobile.urlHistory.getActive();
last_hist.data.pageURL;
The second thought was to override the back button behavior so that the back button from the Wine Detail view would always go back to the Wine list view
$('div#wine_detail').live('pageshow',function(event, ui){
$("a.ui-btn-left").bind("click", function(){
location.replace("/wines/{{wine.wine_type}}/#");
});
});
There is probably a better way to do this, but I'm a bit out of ideas.
Update:
So I continue to hack on this with somewhat negligible results. On thing I have found was this is what I basically need to work: window.history.go(-3)
from the console it does exactly what I need.
So I tried binding it the the back button like such:
$('div#wine_detail').live('pageshow',function(event, ui){
var last = $.mobile.urlHistory.stack.length - 1;
var last_url = $.mobile.urlHistory.stack[last].url;
var review_url = /review/g;
if (last_url.match(review_url) )
{
$('div#wine_detail a.ui-btn-left').bind( 'click', function( ) {
console.log("click should be bound and going back in time...")
window.history.go(-2);
});
}
else
{
console.log('err nope its: ' + last_url);
}
});
No dice, something interupts the transaction...
I'd prefer not to splice/pop/push with the urlHistory. How about redirect on pagebeforechange like so:
$(document).on("pagebeforechange", function (e, data) {
var overrideToPage;
// some for-loop to go through the urlHistory TOP>DOWN
for (var i = $.mobile.urlHistory.activeIndex - 1; i >= 0; i--) {
// this checks if # = your target id. You probably need to adapt this;
if ($.mobile.urlHistory.stack[i].url = $('#yourPageId').attr('id')) {
// save and break
overrideToPage = $.mobile.urlHistory.stack[i].url;
break;
}
// set new Page
data.toPage = overrideToPage;
}
});
This captures your back button changePage call and redirects to the page you want. You could also just set data.toPage = winelist directly of course.
I'm only doing this with #internal pages, but it shoudn't be so hard to set this up with winelist.html etc.
For more info, check the event page in the JQM docs
Why not have a back button in the header section of your page? Something like this:
<div data-role="header">
<a data-direction="reverse" data-role="button" href="#winelist" data-icon="back">Back</a>
<h1>Wine Detail</h1>
</div><!-- /header -->
I wrestled with this recently as well. After thinking about it, I realized I could rewrite my JQM application to use Pop Up "windows" for those pages that I didn't want in my history. This ended up being an easier and cleaner fix than mucking around with browser history.
Now users can intuitively use the browser back button, and I don't have to code application back buttons.
The only thing you have to ensure is that the popups don't themselves make it into the browser history, so make sure to set the "history" option to false like so:
$('#some_popup').popup( { history: false } );
Okay so the solution was close to the update I posted. The issue with the previous solution was that there were to many things bind-ed to the "Back" button. While my new bind action may have been working sometimes, the other actions would take place too, I tried unbind() but still no worky.
My solution is a bit of smoke and mirrors. I check to see if the the previous page was the review page and then if so, I swap out the old back button for my new faux button with the history back step like so:
$('div#wine_detail').live('pageshow',function(event, ui){
var last = $.mobile.urlHistory.stack.length - 1;
var last_url = $.mobile.urlHistory.stack[last].url;
var review_url = /review/g;
if (last_url.match(review_url) )
{
$('a.ui-btn-left').replaceWith('<span class="ui-btn-inner ui-btn-corner-all"><span class="ui-btn-text">Back</span><span class="ui-icon ui-icon-arrow-l ui-icon-shadow"></span></span>');
$('#time_machine').bind( 'click', function( ) {
console.log("click should be bound and going back in time...")
window.history.go(-3);
});
}
else
{
console.log('err nope its: ' + last_url);
}
It looks exactly the same, and no one is the wiser. it could probably be improved by using the the jQm method pagebeforeshow so user could never see the swap. Hope this helps someone.
If you have the situation that you want the close button refer to an arbitrary (not the last) page, you could also change first to the target page and open the dialog afterwards. Therefore the close button at the dialog will open the target page.
// First: change to the target page
$.mobile.changePage('#target_page');
Afterwards open the dialog like this.
// Second: change to the dialog
window.setTimeout(
// for some reason you have to wrap it in a timeout
function(){
$.mobile.changePage('#dialog');
},
1
);
Now you can open the dialog and the close button will open #target_page.
Advantages:
solution works for single dialogs rather than removing all close buttons from all dialogs
seamless integration on a single point of code
history manipulation is not needed
I have seen similar issues before when using jquery mobile and it is addressed in the documentation. When setting up your Javascript "at the beginning of your page" use pageinit instead of ready or maybe in your case pageshow. I think this will address your issue without having to workaround the history queue.

Categories

Resources