简体   繁体   English

在提交表单按钮中添加JavaScript

[英]add javascript in submit form button

I'm trying to put a javascript code in my form submit button. 我正在尝试在表单提交按钮中放置一个javascript代码。

   $('#BtExcluir').click(function(event){
      var urlParams = event.target.href.split("/");
      if (! confirm("Tem certeza que deseja excluir o usuário?")) 
         return false;
   });

The code above works properly with <a> element, but It's not working with input submit button. 上面的代码可与<a>元素一起正常使用,但不适用于输入提交按钮。 Please, help-me! 请帮我!

http://jsfiddle.net/f5Xfw/3/ http://jsfiddle.net/f5Xfw/3/

My full code: @{ Page.Title = "Editar Usuário"; 我的完整代码:@ {Page.Title =“ EditarUsuário”;

// Inicializar variáveis.
int selectedUserId = -1;
var email = "";
var nome = "";

List<string> statusMessages = new List<string>();

// Get the values from the REST-style URL parameters
selectedUserId = UrlData[0].AsInt(-1);
if (selectedUserId < 0){
    ModelState.AddFormError("Erro: Especificado ID de usuário inválido");
}

if(Request["action"] == "Alterar"){
    nome = Request.Form["nome"];
    email = Request.Form["email"];
    // Valida o nome do usuário
    if (nome.IsEmpty())
    {
        ModelState.AddError("nome","Um nome deve ser informado.");
    }
    // Valida o endereço de email
    if (email.IsEmpty())
    {
        ModelState.AddError("email","Um endereço de email deve ser informado.");
    }

    if (!email.IsEmpty() && !Functions.IsValidEmail(email)) {
        ModelState.AddError("email","O endereço de email informado não é válido.");
    }        

    if (ModelState.IsValid)
    {
        // Verifica se o email está cadastrado
        var user = Usuario.PesquisarEmail(email,selectedUserId);
        if (user == null) {
            if (Usuario.AlterarUsuario(nome, email, selectedUserId) > 0)
            {
                statusMessages.Add(String.Format("Alterado usuário de {0}",nome));
            }
            else
            {
                ModelState.AddFormError(String.Format("Erro: Não foi possível alterar o usuário de  "
                            + "{0}", nome));
            }
        }else{
            ModelState.AddFormError("O endereço de email informado já está em uso.");
        }
    }  
}

else if(Request["action"] == "Excluir"){
    if (Usuario.ExcluirUsuario(selectedUserId) > 0){
        statusMessages.Add("Excluído usuário de ID = " + selectedUserId.ToString());
        selectedUserId = -1;
    }
    else{
        ModelState.AddFormError("Erro: Não foi possível excluir o usuário de ID = "
            + selectedUserId.ToString());
    }
}

else if(Request["action"] == "Voltar para Lista"){
    Response.Redirect("~/Admin/Usuarios/Listar.cshtml",false);
}

else if(Request["action"] == "Novo"){
    Response.Redirect("~/Admin/Usuarios/Cadastrar",false);
}

} ​ }

You are saying event.target.href but input buttons do not have an href property - that's an anchor element thing (which is, obviously, why it worked for your <a> ). 您说的是event.target.href但输入按钮没有href属性-这是一个锚元素(显然,这就是为什么它对您的<a>起作用的原因)。 So event.target.href is undefined and thus doesn't have a .split() method. 因此event.target.href是未定义的,因此没有.split()方法。 This is an error and execution will stop at that line and never get to the if (!confirm(... . 这是一个错误,执行将在该行停止,并且永远不会到达if (!confirm(...

Given that you never actually use the urlParams variable you could just delete that line. 鉴于您实际上从未使用过urlParams变量,因此可以删除该行。

Otherwise, the form equivalent of the href is the action , so maybe something like this: 否则, href等效形式就是action ,所以可能是这样的:

$('#BtExcluir').click(function(event){
  var urlParams = $(this).closest("form")[0].action.split("/");
  if (! confirm("Tem certeza que deseja excluir o usuário?")) 
     return false;
});

Note also that within the event handler this will be a reference to the element the event belongs to - it's simpler than saying event.target . 还要注意,在事件处理程序中, this将是对事件所属元素的引用-比说event.target更简单。

1st. 1号 I see you have submit buttons for edit , delete , new and back to the list options. 我看到您有用于editdeletenewback to the list选项的submit按钮。 You won't be submitting all those 4 with the same default form action . 您将不会使用相同的默认form action提交所有这4个。

Therefore, you'll have to either add event.preventDefault(); 因此,您必须添加event.preventDefault(); to your submit buttons' function, or replace them by common buttons where you can handle the redirects manually. submit按钮的功能,或将其替换为可以手动处理重定向的常用按钮。

2nd. 2号 If you had a fully-working function with links, rollback it to the links version to save a lot of work. 如果您具有可正常使用的链接功能,请将其回滚到链接版本以节省大量工作。 =] =]

3rd. 第三名 Don't forget to commit to the Portuguese Stack Overflow proposal in Area 51 . 不要忘记提交51区葡萄牙语堆栈溢出建议。
(shameless promoting) (无耻的推广)

I can also make a chat room if you ever have issues which you can't resolve here. 如果您遇到无法在此处解决的问题,我也可以创建一个聊天室。 =] =]

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

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