1

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

4 Answers 4

2

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()" />
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.