Laurence
Laurence

Reputation: 7823

How to implement a confirm dialog box with If condition in JQuery/Javascript with Asp.net

I have a bit of Jquery (sort of mixed with traditional javascript) to check a textbox. On my sample asp page, there is a button, a textbox and on code behind there is a button_click event. What I am trying to get is, when someone clicked on the button, if the textbox is empty, they will see a alert box. When there is a value, they will see a confirm dialog box. My code does most of the job but when the user see confirm dialog box, and cancel, the server side code got executed.

What am I missing here?

Thanks in advance.

$(document).ready(function () {
    $("#Button1").click(function (e) {

        var a = $("#TextBox1").val();

        if (jQuery.trim(a).length > 0) {
            confirm('To confirm  click OK ');
        }
        else {
            alert("Empty");
            e.preventDefault(); 
        }
    });
}); 

Upvotes: 1

Views: 8073

Answers (4)

Mada Osotnas
Mada Osotnas

Reputation: 20

Use function below for button or a href with class defined when onclick

$("body").on("click",".yourclassname",function(){
    var delet = confirm('Are you sure want to delete?');
    if(delet){
        // Some function when true
    }else{
        // Some function when false
    }
});

Upvotes: 0

IUnknown
IUnknown

Reputation: 22478

use function below for button's OnClientClick property:

 function checkClick() {
      var result = $.trim($("#<%= TextBox1.ClientID %>").val()).length > 0;
      if (result === true) {
           result = confirm("To confirm  click OK");
      }
      else {
           alert("oops!");
      }
      return result;
 }

 <asp:Button runat="server" Text="Click Me" OnClientClick="return checkClick()" />

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148744

Confirm : result is a boolean value indicating whether OK or Cancel was selected (true means OK).

           if (!confirm('To confirm  click OK ')) return false; //don't do anything

Upvotes: 1

jbabey
jbabey

Reputation: 46657

You need to prevent the default behavior (which I assume is a a submit) if they press cancel on the confirm. confirm returns a boolean which will allow you to do this.

if (jQuery.trim(a).length > 0) {
    var answer = confirm('To confirm  click OK ');

    if (!answer) {
        e.preventDefault(); 
    }
}

Upvotes: 1

Related Questions