sorry if my english is poor.
I've a question, i think that the problem is my poor knowledge of javascript but.. i know that you can help me about this.
i've a page with an imagebutton, i use this for delete data and i need a confirmation dialog box. Alertify is pretty, i use altertify alert in server side like this:
string myScript2 = "alertify.error('message.')";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),
Guid.NewGuid().ToString(), myScript2, true);
return;
and work fine!
but i don't understand how to use alertify.confirm.
for example i've used
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../../js/alertify.min.js"></script>
<!-- include the core styles -->
<link rel="stylesheet" href="../../js/alertify.core.css" />
<!-- include a theme, can be included into the core instead of 2 separate files -->
<link rel="stylesheet" href="../../js/alertify.default.css" />
<script type="text/javascript">
$("#btElimina").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
but nothing to do...i can't use onclientclick because alertify is a non-blocking instead a modal windows...
can you help me to understand? not to write code for me, but, to understand and make me viable
thank you
Henry
Replace alertify.success("You've clicked OK"); with return true;
and alertify.error("You've clicked Cancel"); with return false;
Also change this:
$("#btElimina").on('click', function () {
to this:
$("#<%=btElimina.ClientID%>").on('click', return function () {
I used this and it is working:
My button is :
<asp:ImageButton ToolTip="Çıkış" ID="ImageButton1" ImageUrl="Image/Exit.png" runat="server" OnClick="btnLogout_Click" />
My script is:
<script type="text/javascript">
$("#ImageButton1").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
__doPostBack("<%=ImageButton1.UniqueID%>", "");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
Here when i clicked "cancel" button returns false and doing nothing but when you clicked ok button i am doing postback for related button and you can write your own code in server side
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("~/Login.aspx");
...
}
I can't comment on the last comment below as I don't have 50 reputation, so I'm posting an answer simply to elaborate on Ratna's answer.
As per Ratna's answer, you should use server tags to refer to ASP.Net controls (controls with runat="server") to ensure that you get the control regardless of what ASP.Net renames the control to.
So to reiterate Ratna's answer:
Instead of
$('#btElimina').on(..
use
$('#<%= btElimina.ClientID %>').on(..
to make sure that you get the correct clientside control id in your jQuery script.
Related
I am developing an ASP.NET web application. in which have a home page,
when we press F2 in home page we need to load item Master page &
when press F4 in home page we need to load city Master page.
I don't know how to open these pages in ASP.NET C# using short cut keys..
Can any one help me?
write a javascript code onkeypress
function keypress() {
switch (event.keyCode) {
case ascii of f2:
//redirect/or load item master
}
}
or
<script type="text/javascript">
document.attachEvent('onkeyup', KeysShortcut);
// Now implement the KeysShortcut
function KeysShortcut ()
{
if (event.keyCode == 49)
{
document.getElementById('<%= button1.ClientID %>').click();
}
}
</script>
Using linkbutton Example...
C#
Note : The javascript, depending on the keycode, invokes the click event of the element, in our case the link button. The element is obtained by using document.getElementById(' '<%=Control.ClientID%>'').
Note: While using Master Pages, you need to refer to the control using the control's ClientID. I have directly used the ID generated.
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript" src="shortcut.js"> </script>
</head>
Page 1
Add a javascript file to the project called shortcut.js. Add the following code to the javascript file.
function HomeKey()
{
if(event.keyCode == 72)
{
document.getElementById('ctl00_ContentPlaceHolder1_btnHome').click();
}
}
now on backside
C#
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Home", "document.attachEvent('onkeyup',HomeKey);", true);
}
I am calling a JS function from Codebehind, the function is supposed to toggle() or show() a tr in the dom. I am using the following for this purpose:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "ToggleTr(1)", true);
If I am in a debugging mode, this works fine magically, but seems to work very spontaneously otherwise. Hence, I used a timeout 500 for this, but I believe that is not a good approach in itself. So my other try was:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "window.onload = function() {ToggleTr(1);}", true);
But this does not help either. NOTE: I am using webform aspx pages templated under a MasterPage, So I cannot use the head or a form tag either. This is what I have in my aspx page:
<asp:Panel ID="pnlEmployeeDetails" runat="server">
<script language="javascript" type="text/javascript">
function ToggleTr(showFlag) {
if (showFlag == 1) {
$("#trSupervisor").show();
}
else if (showFlag == 0) {
$("#trSupervisor").hide();
}
}
</script>
Secondly, I am not calling this on PageLoad, the calls vary on several event handlers executed.. What should I do here??
I have written the code on
ascx script:
<script src="JScripts/jquery.alerts-1.1/jquery.alerts.js" type="text/javascript"></script>
<script>
$(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
</script>
and on
Code behind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
the problem is alert box is automatically getting disabled after some time when page load fully
What could be the reason that the alert box is being disable after clicking on OK button and how to call the callAlert function in proper way.
If you are using Master page or pages then you won't get the Client Id of the button as you are declared it should be declared as $('#<%=ImageButton1.ClientID%>') or $('[id$=ImageButton1]') hope it will solve you problem.
$(document).ready(function(){
$('#<%=ImageButton1.ClientID%>').click(function() {
alert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
You can try to put the following line before the function
$(document).ready(function() {
This will make it:
$(document).ready(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
});
If you wait till the page is ready, the alert box won't be overwritten (I hope x)).
Also when you check that text box, check if the condition is false, then give the alert.
Is the condition not false? Build in a check to check if the condition is really true. If so? Redirect.
EDIT:
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
//redirect
else
return
OK, so first it's important to understand that $(function(){... and $(document).ready(function() {... are equivalent, and nothing inside either will execute until the page is fully loaded. In other words, there's no need to use
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
That can be removed. Also, I see that you're probably using web forms. Be mindful that the Id attribute that will be rendered is not equal to the Id of the control attribute. In other words, if you have a runat="server" control with an Id of ImageButton1, using the syntax $('#ImageButton1') in your jQuery won't work.
Taking this into account, I've added an example below that uses selectors based on class attributes.
<script type="text/javascript">
$(function () {
$('.ImageButton1').click(function (e) {
var text = $('.TextBox1').val();
var redirect = true;
if (!text) {
redirect = confirm('Empty...are you sure?');
}
if (redirect) {
window.location.href = 'http://your-redirect-here.com';
}
});
});
</script>
<input class="TextBox1" type="text" />
<input class="ImageButton1" type="button" value="Click" />
That should get you where you want to go. Let me know if you have any questions.
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
{
//redirect
} else
{
return false;
}
Put this after jAlert Box:
return false;
And call the function like this:
return callAlert();
I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
I have a simple content management system that stores pages by Pagename and Version. After clicking on Save, my code (server side) checks for the existence of Pagename/Version.
If it exists I would like to display a confirmation dialog box, which asks the user to confirm whether or not the current Pagename/Version should be replaced.
What is the easiest way to accomplish this? Thanks.
<asp:Button OnClientClick="return confirm('Are you sure you want to go?');"
Text="Confirm" runat="server" onclick="Unnamed1_Click" />
If they click OK, the server onclick event will happen, if they click cancel, it will be like they didn't even press the button, of course, you can always add functionallity to the cancel part.
Maybe something like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript">
function CompareConfirm()
{
var str1 = "abc";
var str2 = "def";
if (str1 === str2) {
// your logic here
return false;
} else {
// your logic here
return confirm("Confirm?");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button OnClientClick="return CompareConfirm();"
Text="Confirm" runat="server" onclick="Unnamed1_Click" />
</div>
</form>
</body>
</html>
I appreciate both previous answers and they were helpful but not exactly what I was looking for. After considering the responses and doing more research I'm posting my solution so that maybe it will help someone else.
Button code:
<asp:Button ID="btnSave" OnClick="btnSaveClick" runat="server" Text="Save" OnClientClick="return CheckForVersion()" />
Javascript:
<script language="javascript">
function CheckForVersion() {
PageMethods.CheckForVersion(aspnetForm.ctl00$ContentPlaceHolder1$ddlPageName2.value, aspnetForm.ctl00$ContentPlaceHolder1$txtContentName2.value, OnSucceeded, OnFailed);
return false;
}
function OnSucceeded(results) {
if(results) {
//version exists so prompt user
if(confirm("Version already exists. Do you want to overwrite?")) {
__doPostBack('ctl00$ContentPlaceHolder1$btnSave','');
}
}
else
{
//version does not exist so save it without prompting user
__doPostBack('ctl00$ContentPlaceHolder1$btnSave','');
}
}
function OnFailed(error) {
// handle pagemethod error
alert(error.get_message());
}
</script>
C# using Subsonic 2.1:
[WebMethod]
public static bool CheckForVersion(string pageName, string versionName)
{
PageContentCollection pages = new PageContentCollection().Where("pageName", pageName).Where("versionName", versionName).Load();
if (pages.Count > 0)
return true;
else
return false;
}
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks.
If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button.
In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
add a hidden field to your page for example Hiddenfield1
then add this function
public bool Confirm(string MSG)
{
string tmp = "";
tmp = "<script language='javascript'>";
tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;";
tmp += "</script>";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp);
if(HiddenField1.Value.Trim()=="0") return false;
return true;
}