Reloading the page only once on a button click - javascript

I have a Load button and I am calling onclick event on that button which would refresh the page using window.location.reload() . But ,what I want is that the reload should only be called when the button is clicked for the first time . From the second click and till the HTML page is active the reload should not be called .
How can this be achieved with javascript ?Any examples would be helpful.

You could use local storage or session storage to do that. This is a modern approach that makes use of Web Storage API.
In this case, you may set a property in the storage to hold the button click and only do the refresh if it is not yet clicked.
It is possible to do it like the following snippet:
$('button').on('click', function() {
// will return null at the first call
var buttonClicked = sessionStorage.getItem('isButtonClicked');
// will only enter if the value is null (what is the case in the first call)
if (!buttonClicked) {
// set value to prevent further reloads
sessionStorage.setItem('isButtonClicked', true);
// reload the page
window.location.reload();
}
});
A more detailed example on the web storage API can be found here, if you want to know more details about it.

One way to handle this would be changing the action that onClick performs. Try taking a look here: Change onclick action with a Javascript function

You can try sending a parameter on the first reload and using that parameter change the action of the button.
Something like:
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var secondReload= getQueryVariable("secondReload");
if(!secondReload){
//if button clicked
window.location.reload();
}else{
//deactivate button
}
</script>

you need to add a disabled attribute on the button tag within the click event.
Reloading the page only once on a button click
if you're using jQuery, something like this.
$('button').on('click',function()({
... your code here
$(this).attr('disabled');
});

Related

On load function checking for button controle

I inherited VScript code that will create a web service redirect button based on logged in user; if the user is not found the button is not created and error text is displayed, I was asked to set up onload javascript function to automatically click the button-that i did.I need to check if the button exists first before i click it.What is the best way to do check if the button exist onload in javascript?
Thnaks
This should work fine:
var button = document.getElementById("the button's id");
window.onload = function() {
if (button != null) {
// your code
}
}

Not opening new page throught JavaScript

I have a script that gets throught parameter the new page andthe redirects to this page.
my function:
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://localhost:8080/Edas/" + page; //not working
}
and my button:
<button id="btnViewMonthlyPurchaseReport" onclick="openPage('monthlyPurchaseReport.html')">View Monthly Purchase Report</button>
I think my problem is in my base URL ("localhost:8080/Edas/"), but really don't know how to fix it.
Thanks!!
Out of the comment the problem was that the button was inside of a form element.
The problem is that a button without a type attribute will submit the form, which would (not sure if in every browser) result into the described problem, that the window.location.href = ... has no effect and that the page would be redirected to the url defined in action. If action is not defined in the form then it is the the current url.
You have different options to solve this:
You could move the button out of the form (if it would not affect usability)
Change the type of the button to button (<button type="button">View Monthly Purchase</button>) - the default behavior without a type is submit
You could place a return false; at the end of your openPage function to prevent the default behavior (this is similar to 2. but with the difference that the button would still be marked as a submit button which could be important for usability in some situations).
Do this:
JS
var url = window.location.href;
var dirnames = url.split('/');
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://"+ dirnames[2] +"/Edas/" + page;
}
I imagine you're correct in saying that your issue is in the URL.
Where is your monthlyPurchaseReport.html? If it is in the same directory as where the html with your button is, simple use:
function openPage(page) {
alert("Pressed the button!");
window.location.href = page;
}
My problem was: my button was wrongly inside a form, which #t.niese clearly explained why.
Thank you all for the help!

Javascript - keep the button disabled on all pages

I have a javascript function as below.
$("#update").click(function (){
this.disabled = true;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
$("slider:changed")
Once I click on the button for updating the values, I am trying to disable the button. However, since I am using pagination, if I navigate to the second page, my button re-enables again. Is there any way to keep it disabled across all the pages?
This is the link to my work so far.
Use localStorage, or a cookie, to store the "true/false" value of the button. Check that value on every page load and assign its value back to the button's disabled property.
In your click handler, after "this.disabled = true", add:
localStorage.setItem("updateDisabled", true);
Then check for the value again on page load:
$(function () {
var disabled = localStorage.getItem("updateDisabled");
if (disabled) $('#update').attr('disabled', disabled);
});
You need to do one of two things: (1) pass the variable back to your server in some way, or (2) pass it through to the next page. You can do (1) with AJAX or a cookie, and you can do (2) with a URL parameter or a cookie. The web is "stateless," meaning (among other things) that each page doesn't know anything about what just happened on another page, unless you pass that information along somehow.

Page does not redirect when setting window.location in JavaScript

I am trying to redirect the page dynamically depending upon the value of the dropdown box.
I get the value of drop down box in JavaScript. Depending on the dropdown value I want to redirect the page.
This is sample code:
<script type="text/javascript">
function RedirectMe(){
var chosanDept = document.getElementById("Dept");
var str = chosanDept.options[chosanDept.selectedIndex].text;
if(str=='HR')
{
alert('Yes in IF' + str);
window.location = "http://www.google.com";
}
}
</script>
here
chosanDept is the variable to get the value of dropdown box. But I am not able to redirect page using various function like
window.location, location.replace, location.href.
And one more my if condition works, I get the alert 'Yes in IF HR'
What goes wrong here?
Try adding return false; to the end of your RedirectMe() function
And then wherever you are calling the function, make sure you put return there, like onclick="return RedirectMe();"

Disable IE back Button

I have a application where i have disabled the back button of IE8 by using the following code.
window.history.forward();
function noBack() {
window.history.forward();
}
I know this code takes the page back and again moves the page forward. i have called a function onload of the page which makes a textbox read only. i have used the following code to make it read only.
$("#IDofTheTextBox").attr('readonly',true);
but if i select the textbox and try to edit by pressing "BackSpace" button, IE back button is getting invoked and the textbox which was readonly is not readonly anymore. Can anyone help me how to solve this issue?
The answer is simply "NO"
If you're trying to prevent the user from losing their work, try something like:
window.onbeforeunload = function() { return "Are you sure want to leave this page?."; };
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
You add the above javascript functions in the js file and onload call the function changeHashOnLoad().
its working fine in IE8. i just tested it.
I dont know what your page is trying to do... but this is what we do:
We have an assessment where we do not want the browser buttons enabled... because we run ajax/logic when the user hits next/back etc (to determine what to display next based on their inputs). Back and forward buttons can muddy that process up.
So..... we have users open our assessments in A NEW WINDOW so the back button is already disabled...(there is no prior history in a new window). Then, Our next/back buttons use window.location.replace(url); This will prevent a history item from being created. Therefore, the back/forward buttons are never enabled and they must use the next/prev buttons to navigate our tool.
I would not try to muck with the buttons outside of something like the example I provided.

Categories

Resources