I want to add a simple confirm, are you sure dialog when you click an asp:button which does postback.
Something like:
OnClientClick="if(confirm('Format the hard disk?'))
alert('something');
else alert('something else')"
Problem is that whether you click ok or cancel it still posts back.
How to make it so that it only posts back on OK?
If you're just looking to do a postback based on the selection from the confirmation dialog, this might be simpler:
OnClientClick="return confirm('Are you sure?');"
Also you can use next:
OnClientClick="return confirm('Delete this entity?');"
In short "....; return false;" stops the click, example below not using inline JS:
Markup:
OnClientClick="confirmSomething()";
JS Function:
function confirmSomething()
{
var result = confirm('Format the hard disk?');
if(result == 1)
{
alert('something');
return true; //continue click event
}
else if(result == 0)
{
alert('something else');
return false; //stop click event
}
}
you need to return the confirm instead.
see: http://rumandcode.wordpress.com/2008/08/11/javascript-confirm-on-aspnet-button/
Use return false.
OnClientClick="if(confirm('Format the hard disk?')) alert('something'); else {alert('something else'); return false;}"
Related
Is it possible to use the onclientclick property of a button to do a clientside check. If the check returns true, then fire the onclick event. If the clientside check returns false, don't fire the onclick event.
Is that possible?
UPDATE:
These 2 work:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
The next 2 do not work:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
It submits the form both times.
Why is that?
You want to add return inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.
<asp:button ID="Button1" runat="server" OnClick="Button1_Click"
OnClientClick="return checkValidation()" Text="Submit" />
<script type="text/javascript">
function checkValidation() {
return confirm('Everything ok?');
}
</script>
Sure. If you use return false within your OnClientClick it will prevent any navigation from happening. So you're code would look like:
<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Yes you can, In onclientClick function call use preventDefault()
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
e.preventDefault();
}
}
OR
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
return false;
}
}
In the server page create the button:
var button1 = new Button();
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );
//Contains the server code
private void saveBtn_ServerClick(object sender, EventArgs e)
{
//do something if ClientClick returns true
}
//Contains the JS code for the page
LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =#"<script type='text/javascript'>
$(document).ready(function(){
function CheckValidationOnClient(){
if(!ValidatePage()){
return false;
}
else{
return true;
}
};
});
</script> ";
private string SetJsForSaveBtn()
{
var jsfunc = #" return CheckValidationOnClient()";
return jsfunc ;
}
I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.
However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.
namespace My.WebControls {
[ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
public class LinkButton : System.Web.UI.WebControls.LinkButton {
private bool _postback = true;
[Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
public bool AutoPostBack { get { return _postback; } set { _postback = value; } }
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
if(!AutoPostBack){
this.OnClientClick = "return false";
}
base.Render(writer);
}
}
}
Many attributes should need to be handled in a ViewState but in this case I think we are good;
I m working on a web application that contains a text box. The value of text box is filled from Date picker and its property is read only by default. till now everything is working fine. But problem occurs when I press backspace button. Rather than clearing the text box it is redirecting me back on the previous page.
i handled this situation by a javascript function by referring some previous answers on this site.
function allowBackSpace(val) {
var keyCodeEntered = (event.which) ?
event.which :
(window.event.keyCode) ?
window.event.keyCode :
-1;
if (keyCodeEntered == 8) {
$(this).val("");
return true;
}
return false;
}
UPDATE : this function is called from
<asp:TextBox ID="txtDate"
Style="margin-left: 5px; margin-right: 5px"
runat="server"
Width="88px"
onkeypress="return allowBackSpace(this);">
</asp:TextBox>
I m calling this function on key press event of the textbox. The preoblem is that it is allowing only to delete one character at a time.
I wish to clear the whole textbox if user presses backspace button. Stuck here as how to achieve this.
Thanks in advance
Akhil
PS:Any way to achieve this using C# code will also be very helpful.
You are returning true from js function, which also performs its keypress event. So, try with returning false.
You can try the following code:
function allowBackSpace(val) {
var keyCodeEntered =
(event.which) ? event.which :
(window.event.keyCode) ? window.event.keyCode : -1;
if (keyCodeEntered == 8)
{
$(this).val("");
return false;
}
return false; }
Try this function.
$("#txt1").keydown(function(eve){
var keyCodeEntered = eve.keyCode? eve.keyCode : eve.charCode;
if (keyCodeEntered == 8)
{
$(this).val("");
return false;
}
return false;
});
});
Use Jquery
$("#txtDate").keyup(function(event){
if(event.keyCode == 8){
$("#txtDate").val("");
return false;
}
});
function allowBackSpace(e,obj)
{
var evt=e||window.event;
if(evt.keyCode==8)
{
obj.value='';
}
}
Now, use onkeydown event instead of onkeypress
<textarea onkeydown='allowBackSpace(event,this)'></textarea>
So I've got this button:
<asp:Button runat="server" ID="btnSubmit" meta:resourcekey="btnSubmit" CausesValidation="true" OnClick="btnSubmit_Click" />
meta:resourcekey is for Localization Resources, doesn't concern us here - as we can see it has got an OnClick-Method and causes Validation.
That works fine, too, but I'd like to disable that button after the user clicked it so he/she can't click it multiple times before the PostBack succeeds, so here's what I did in Page_Load:
btnSubmit.Attributes.Add("onclick", "this.disabled=true;" +
Page.ClientScript.GetPostBackEventReference(btnSubmit, "").ToString());
onclick I'm disabling the button and re-adding the PostBackReference necessary for the OnClick-Method.
Problem: CausesValidation is gone, sadface. How exactly would I re-add that in CodeBehind or alternatively - What's an entirely different solution to this?
My Button has to:
a) disable itself after clicking, yet be enabled after the postback
b) have an OnClick CodeBehind Method
c) cause Validation
Thanks,
Dennis
Just override the Onload event of ur page or master page with
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// prevents form from being submitted multiple times in MOST cases
// programatic client-side calls to __doPostBack() can bypass this
Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm",
"if (this.submitted) return false; this.submitted = true; return true;");
}
Try the following in Page_Load
VB
Dim postBackOptions As PostBackOptions = New PostBackOptions(btnSubmit)
btnSubmit.OnClientClick = "this.disabled=true;"
btnSubmit.OnClientClick += ClientScript.GetPostBackEventReference(postBackOptionClaim)
C#
PostBackOptions postBackOptions = new PostBackOptions(btnSubmit);
btnSubmit.OnClientClick = "this.disabled=true;";
btnSubmit.OnClientClick += ClientScript.GetPostBackEventReference(postBackOptionClaim);
EDIT
if(Page_ClientValidate()) {this.visibility='hidden';}
If you need to have server side validation before you know whether to hide/disable the button or not you'll probably want to forgo the disabling of the button and just make sure your server-side code doesn't execute more than necessary if a user hammers on the button.
You could put a hidden field and generate a GUID for it in the page_load if(!IsPostBack) then on your btnSubmit_click do something like
if(Session[Page.ToString() + "_spam"] != null && Session[Page.ToString() + "_spam"] == hdnGuid.Value) {
return
} else {
Session[Page.ToString() + "_spam"] = hdnGuid.Value;
//do stuff
}
I am using a javascript
function ValueChanged()
{
if (document.getElementById("<%=isDirty.ClientID %>").value != document.getElementById("<%=rdbQuestiontype.ClientID %>").value)
{
if (window.confirm('Your changes are not saved. Do you want to save your changes before you exit.'))
return false;
else
return true;
}
}
this java script i am calling on OnClientClick="return ValueChanged();
I have a Save button on the same page i want to save the data when client click on OK button of cinfirm alert OK btn. Means my onclick="btnsave_Click" event also call and my data get save on confirm message OK btn.
<asp:Button runat="server" ID="btnOK" Text="OK" OnClientClick="Javascript:return confirm('Your Message')" OnClick="btnOK_Click" />
I have change something in javascript
if (document.getElementById("<%=isDirty.ClientID %>").value != document.getElementById("<%=txbText.ClientID %>").value)
{
var ssave = window.confirm('Your changes are not saved. Do you want to save your changes before you exit.')
if (ssave == true)
{
document.getElementById('<%=btnSave.ClientID%>').click();
return false;
}
else return true;
}
So I'm putting together a little registration area for my web project, here. The user inputs various strings such as "Username", "Password", etc.
I already have a bit of code set up in order to prevent duplicate Usernames or Passwords in the database. I also have a guard in place if the "Password" and "Repeat Password" fields don't match.
What I'm trying to do now is to -
1: If the user attempts to Submit data while a field is blank, it will not post.
2: Display a "Fields cannot be blank" div I've assigned "display: none" to.
I was thinking something along the lines of assigning the input fields a class of "Required", and using some sort of code such as
if == null
.show;
return false; //To prevent the rest of the function (the submit button posting to login/register) from firing.
Running into obscene problems. Anyway. Here's what I have so far.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
});
Any thoughts? At first I thought that I literally -cannot- use "class" to mark an input field, and then have that input field compared to a null value. I don't know, though.
You should use the .submit() jquery event handler on the form instead of .click() on the button. Then return false to prevent the normal form submission if needed.
Since you are trying to submit the form using $.post you should stop the default behavior of the form submit by alwasy returning false from submit button click handler.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
return false;
});
The jQuery way of preventing form submission is to use preventDefault(), like:
$("#SubmitButton").click(function (event) { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
event.preventDefault(); //And nothing else fires
return;
}
//...
});
However, since you are posting the form asynchronously when validation passes, what you really want is something more along the lines of:
$("#SubmitButton").click(function (event) { //Click Submit
event.preventDefault(); //we don't ever want to allow the default behavior
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
});
The rest of what you suggest (using a class to mark each required input field, checking them all for empty strings) is reasonable.
Be aware that because you are binding the button's click event instead of the form's submit event it is entirely possible for the user to submit your form without ever clicking on your button and triggering your validation code. For instance, by pressing return from any one of your text fields.
Also note that in this case you may find it more convenient to just use a traditional onsubmit directive on the form, like:
<form onsubmit="validateAndPost(); return false;">
<!-- inputs and buttons, etc. -->
</form>
<script>
function validateAndPost() {
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
}
</script>
Example: http://jsfiddle.net/AwxGE/
I admire your desire to use jquery, however I would advise using a normal ASP.NET ReqiredFieldValidator control. As well as making your page substantially more concise and easy to maintain, it also allows you to very simply invoke server-side validation:
public void submitbutton_click(object sender, EventArgs args){
Page.Validate();
if(Page.IsValid){
doStuff();
}
}
Please don't reinvent the wheel, and don't trust the browser to behave as you think it will.
use this -
$(document).on('click', '#SubmitButton', function () {
`enter code here`
});