On load function checking for button controle - javascript

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
}
}

Related

Reloading the page only once on a button click

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');
});

An easy way to create a JQuery single field confirmation dialogs for a webpage

This is all I want to do:
User click on an image button
It displays a confirmation dialog with a label and a text field and OK button
If they enter a value and click OK button then returns the value which can then be used to invoke a constructed hyperlink based on the value entered.
If they click on cancel leave value blank then the popup is just dismissed
But the page is generated dynamically and there may be many rows that have an image button that will open the said popup, I dont want to have to add a javascript function for each popup required.
Im already using JQuery a little bit so I think using JQuery Dialog is the way to go but I'm not getting anywhere with actually implementing this seemingly simple task.
I'm looking for a simple example without any extraneous cruft that I dont actually need.
Update With More detail
This is what I currently have in the calling htmnl
There are two buttons within a element, the first is an input button is fine, the second is currently just invokes a hyperlink but it needs a value for the discogsid parameter (currently xxxxx). So I want clicking on the second one to provide user with a way to enter a value and then if they enter something use that as the value of discogsid in the url
<td>
<input title="View tracks in this release" onclick="return toggleMe(this,'232')"
src="/images/open.png" alt="Open" type="image">
<a href="/linkrelease/?discogsid=xxxxxx&mbid=e3c0e7c7-df7c-4b51-9894-e45d1480e7b5" target="_blank">
<img src="/images/link.png"</a>
</td>
Keep it simple :)
try this http://jsfiddle.net/7r1z8v7u/
$("div").click(function() {
var answer = prompt("Pls provide your input");
if(answer != null) myHyperlinkBuilder(answer);
}
Here I have used "div" as selector. Through this, in one shot, we can handle click behavior for all the images.
After that, it is simple JavaScript to display dialog box. Only when the user has enter some input, through if condition we proceed with building our custom URL.
Hope this helps!
Using jQuery you will need to attach an on click event to your link. You can do this in any way you deem acceptable for your application. I'll use a class in my example.
Test
$('.requireQueryEntry').click(GetSearchQuery);
Your click handler will need to prevent the default action since you are using a link. Which means you'll have to reissue your navigation in your code.
function GetSearchQuery() {
var thelink = $(this);
$("#dialogSearch").dialog({
resizable: false,
modal: true,
title: "Search",
height: 180,
width: 340,
buttons: {
"Search": function () {
$(this).dialog('close');
callback(thelink);
},
"Cancel": function () {
$(this).dialog('close');
}
}
});
//This line prevents the default action and the propagation of the event. It only works this way because jQuery handles it that way for us.
return false;
}
function callback(theLink) {
var href = theLink.attr("href");
var target = theLink.attr('target');
var newQuery = $("#googleQuery").val();
if (newQuery.length > 0) {
href = href.replace("xxxxxx", newQuery);
} else {
return; // end the function here when the user enters nothing
}
//This may cause popup blockers
var win = window.open(href, target);
$("#googleQuery").val("");
}
I've put together an example: http://jsfiddle.net/anh7g8eb/2/
My difficulty with both of these solutions was actually get the dialog to be invoked from the html. both solutions used that didn't compatible with my situation.
I worked out that as in the solutions the hyperlink was not actually a hyperlink that if I changed it to a button like I do for the first option things would be easier, so the hmtl changed to
<td>
<input title="View tracks in this release" onclick="return toggleMe(this,'30')" src="/images/open.png" alt="Open" type="image">
<input title="Link" onclick="return promptForDiscogsReleaseId(this,'676fdad7-69b5-4f38-a547-a8320f01ad59')" src="/images/custom_link.png" alt="Link" type="image">
</td>
and added this javascript function that shows a prompt and then creates a new page with the derived hyperlink
javascript function to
function promptForDiscogsReleaseId(btn,mbReleaseId) {
var answer = prompt("Please the Discogs Release Id you want to link this release to:");
window.open("/linkrelease/?discogsid="+answer+"&mbid="+mbReleaseId, "_blank");
}
and it works.

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.

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.

Intercept selection in window.onbeforeunload dialog

in my web application if the user leaves the current page without having saved changes in the form a pop up window is opened to alert him about that.
For the pop up I use some scripts code injected from codebehind (C#):
var Confirm = true;
window.onbeforeunload = confirmClose;
function confirmClose()
{
if (!Confirm) return;
if(/*CHECK CHANGE CONDITION IS TRUE*/)
{ return " + WARN_message + "; }
}
I would need to intercept whether the user click on cancel or ok button.
I tried like:
var button_pressed = window.onbeforeunload = confirmClose;
But it returns always true.
How can get which button was pressed?
Thanks
Not possible. There is no event associated with the buttons.
What you might be able to do was to see if the user came back by setting a value or perhaps a cookie in the page in the onbeforeunload and test if it is there after some time has passed
but see the duplicate Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

Categories

Resources