I'm developing an web application using ASP.NET and C#..
I'm facing an issue, that when I press "F5" or "refresh button", after changing value in dropdown list, it changes back to first value..
But if I press "Ctrl+F5", the dropdown list is not changing..
After analysis I found Ctrl+F5 is doing force reload..
So now I want to do same thing when I press F5 or refresh button or Ctrl+R also..
How to do that..? I need to identify which browser also.. Because this happen only in Firefox..
Also, where (which event) I've to do that coding..?
I think the best way to solve this issue is to save the selected value of your drop-down list into the web storage using the onunload (or onbeforeunload) event in Javascript.
Then, you just have to get it back after the page loading using the onload event.
EDIT - sample code
So, here is your dropdown list :
<select id="list">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Now, let's see the Js :
window.onload = function() {
window.document.getElementById('list').selectedIndex = localStorage['mySavedValue'];
};
window.onunload = function() {
localStorage['mySavedValue'] = window.document.getElementById('list').selectedIndex;
};
I tested it on a local page on firefox 26.0 (linux) and it worked. See working jsFiddle here
Try this. this will treat F5 and Ctrl+F5 in same way....
<script language="javascript" >
var ctrl = false;
document.onkeydown = function() {
if (event.keyCode == 17) {
ctrl = true;
}
if (event.keyCode == 116 && ctrl == true) {
//alert("ctrl+f5");
window.location.relord();
ctrl = false;
}
else if (event.keyCode == 116 && ctrl == false) {
window.location.relord();
//alert("f5");
}
}
Related
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
I have been using JTable in my aspx pages and all seems well, but on a certain content page, when I try to edit or Add an item in Jtable, and by default I press Enter, the UI becomes vague. Before pressing Enter while Updating Jtable row.
All I want is to when I click Enter, submit jtable , simulate click on Save button on edit and create form.
I can use this:
formCreated: function (event, data) {
data.form.find('input[type="text"]').keydown(function (event) {
if (event.keyCode == 13) {
$('#AddRecordDialogSaveButton').click();
$('#EditDialogSaveButton').click();
event.preventDefault();
return false;
}
})
}
but I must copy that on every jquery jtable form. Is there any simplest way?
I love to share my solution for this problem whit all people who need this:
$(window).keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
$('#AddRecordDialogSaveButton').click();
$('#EditDialogSaveButton').click();
return false;
}
});
Alright my basic question is how do I simulate a button click in javascript.
I know I have to use document.getElementById("btnSubmit").click(); but this doesn't seem to call the onClientClick javascript function as well.
Enviorment:
I am using ASP.NET with C# and javascript.
What happened:
I have an input text area and I want to make sure that users must enter a character before the submit button is enabled. I was able to do this with onkeypress="validateTxt();" which then called this function
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
The only problem though is doesn't register backspace.
To solve this I found this online
<script type="text/javascript">
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
Now whenever the user presses the backspace my javascript function is called. This worked great up until I found out that when I press enter from the text area it wouldn't call my javascript function.
Here is all of the relevant code...
<script type="text/javascript">
function InformUser()
{
window.document.getElementById("loadingMessageDIV").style.display = "block";
<%=Page.GetPostBackEventReference(btnSubmit as Control)%>
document.getElementById("btnSubmit").disabled = true;
}
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
</script>
Here is the text area + javascript bounding function
<asp:TextBox ID="txtUserName" runat="server" Font-Size="11pt" onkeypress="validateTxt();"></asp:TextBox>
<script type="text/javascript">
//We bind the textbox to this function and whenever the backspace key is pressed it will validateTxt
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
</script>
Here is the submit button
<asp:Button ID="btnSubmit" runat="server" OnClientClick="InformUser();" OnClick="btnSubmit_Click"
Text="Login" Font-Bold="True" Enabled="True" />
<script type="text/javascript">
//Disable the button until we have some actual input
document.getElementById("btnSubmit").disabled = true;
</script>
So to recap it does press the button, but it fails to disable it as well. I even tried to call the InformUser directly when the user presses enter and then press the button, but that didn't work either.
I know it has something to do with how I bound the javascript function to the text area because when I take it out it works.
Thanks for the help
If what you're really trying to do is enable/disable the submit button based on the amount of text in the text area, then it would be simplest just to check the length every time it's changed.
Would you be able to use jQuery? If you can, it's a trivial problem, as jQuery normalises keyboard events so you don't have to worry about different browsers raising different events.
As a simple experiment, I created a jsFiddle with this HTML:
<textarea id="txt"></textarea>
<label id="count" />
and this JavaScript:
$('#txt').keyup(function () {
$('#count').text($('#txt').val().length);
});
On every keyup (I used keyup rather than keydown or keypress as keyup fires after the text has been modified) the length is updated. This registers normal keys, backspace, delete, enter, etc, and works in FF and IE8.
In your case, you'd obviously change the function to enable/disable the submit button.
I would like to know how (if there's a way) to handle multiple link clicks via the ctrl key.
So for example the user would go to a web page with about 3 hyperlinks on it. Then the user would hold down the ctrl key, then click one link then another. Then when the ctrl key is released, an event will occur (maybe a search based on the combination of both hyperlinks' values).
I am using C# and assume the solution will probably be done in jQuery?
The selection should work similar to how windows explorer does. Where you hold down the ctrl key, then select a file, then another and then cut or paste it somewhere.
I appreciate any help that you could provide as I am struggling to find help elsewhere.
You could do something like this; keep state of the CTRL key (keycode = 17), add links to array when CTRL is pressed down (keydown event), on the keyup event (when keycode == 17) open the links in new windows. Opening them in tabs is not really possible, however there is a working sample for Firefox; read this.
Example:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var ctrlIsDown = false;
var links = new Array();
function afterKeyUp()
{
if(links.length > 0){
for(var link in links){
window.open(links[link]);
}
links = new Array();
$("a").css('color', '');
}
}
$(document).ready(function(){
$(document).keydown(function(e){
if(e.which == 17) {
ctrlIsDown = true;
}
});
$(document).keyup(function(e){
if(e.which == 17) {
ctrlIsDown = false;
afterKeyUp();
}
});
$("a").click(function(e){
if(ctrlIsDown){
var href = $(this).attr("href");
if($.inArray(href, links) == -1)
{
links[links.length] = href;
$(this).css('color', 'red');
}
e.preventDefault();
}
});
});
</script>
</head>
<body>
Link 1
Link 2
Link 3
</body>
</html>
High level idea would be
1) Create a css class to highlight selected link
2) Write javascript function to detect Ctrl key on KeyDown javsacript event of hyperlinks, this function should toggle the class of hyperlinks to selected link (so that user know which hyperlinks are selected) and add the hyperlink value/url to an hidden field to know the links of selected hyperlinks
3) Write javascript function on KeyUp javsacript event on hyperlinks to get the selected links and perform action on it.
We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.