简体   繁体   English

如何使用Asp.net在JQuery / Javascript中使用If条件实现确认对话框

[英]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. 我有一点Jquery(与传统的javascript混合)来检查文本框。 On my sample asp page, there is a button, a textbox and on code behind there is a button_click event. 在我的示例asp页面上,有一个按钮,一个文本框,后面有一个button_click事件。 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(); 
        }
    });
}); 

use function below for button's OnClientClick property: 使用下面的按钮的OnClientClick属性:

 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()" />

You need to prevent the default behavior (which I assume is aa submit) if they press cancel on the confirm . 如果他们在confirm按取消,您需要阻止默认行为(我假设是提交)。 confirm returns a boolean which will allow you to do this. confirm返回一个布尔值,允许你这样做。

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

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

Confirmresult是一个布尔值,表示是选择了OK还是Cancel(true表示OK)。

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

Use function below for button or a href with class defined when onclick 使用下面的功能可以选择按钮或者在onclick时定义类的href

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM