twitter-bootstrap 在表单错误时调用引导程序警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17449714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:31:05  来源:igfitidea点击:

Calling bootstrap alerts on form error

javascripttwitter-bootstrapalert

提问by Novicode

I have the following HTML code for the alert div:

我有以下用于警报 div 的 HTML 代码:

<div id="formAlert" class="alert">  
  <a class="close" data-dismiss="alert">×</a>  
  <strong>Warning!</strong> Make sure all fields are filled and try again.  
</div>

And the following JavaScript:

以及以下 JavaScript:

function validateForm(){
  var x=document.forms['register']['username'].value;
  if (x==null || x=="") {
    alert('This is an alert')
    return false;
        var alertDialog = document.getElementByid("formAlert");
        alertDialog.style.display = "block";
  }
}

The problem with the code is that the alert is showing prematurely, even before the code is called. I can tell the alert is called when the default JavaScript alert box pops up. Ideally, when validateForm()is called, I want the alert to show up. validateForm()is called when the form is submit.

代码的问题在于警报过早显示,甚至在调用代码之前。当默认的 JavaScript 警报框弹出时,我可以告诉警报被调用。理想情况下,当validateForm()被调用时,我希望警报出现。validateForm()在提交表单时调用。

EDIT: As requested, here is the code triggering the validateForm():

编辑:根据要求,这里是触发 validateForm() 的代码:

<form name="register" action="" onSubmit="return validateForm()" method="post">
</form>

Now that I've solved the issue of calling it, how do I hide the div until it's called by the JavaScript, as it's already showing before the code executes.

现在我已经解决了调用它的问题,我如何隐藏 div 直到它被 JavaScript 调用,因为它在代码执行之前已经显示出来了。

回答by Ian

If you reorganize your code, you can separate the JavaScript from the HTML completely and deal with events there. Here's how I'd set it up:

如果您重新组织您的代码,您可以将 JavaScript 与 HTML 完全分离并在那里处理事件。这是我如何设置它:

<div id="main_area" class="row-fluid">
    <div class="span10 offset1">
        <div id="formAlert" class="alert hide">  
          <a class="close">×</a>  
          <strong>Warning!</strong> Make sure all fields are filled and try again.
        </div>

        <form name="register" action="" method="post">
            <input type="text" name="username" />
            <br />
            <input type="submit" class="btn btn-primary" value="Submit" />
        </form>
    </div>
</div>

And the JS:

和 JS:

$(document).ready(function () {
    // Run this code only when the DOM (all elements) are ready

    $('form[name="register"]').on("submit", function (e) {
        // Find all <form>s with the name "register", and bind a "submit" event handler

        // Find the <input /> element with the name "username"
        var username = $(this).find('input[name="username"]');
        if ($.trim(username.val()) === "") {
            // If its value is empty
            e.preventDefault();    // Stop the form from submitting
            $("#formAlert").slideDown(400);    // Show the Alert
        } else {
            e.preventDefault();    // Not needed, just for demonstration
            $("#formAlert").slideUp(400, function () {    // Hide the Alert (if visible)
                alert("Would be submitting form");    // Not needed, just for demonstration
                username.val("");    // Not needed, just for demonstration
            });
        }
    });

    $(".alert").find(".close").on("click", function (e) {
        // Find all elements with the "alert" class, get all descendant elements with the class "close", and bind a "click" event handler
        e.stopPropagation();    // Don't allow the click to bubble up the DOM
        e.preventDefault();    // Don't let any default functionality occur (in case it's a link)
        $(this).closest(".alert").slideUp(400);    // Hide this specific Alert
    });
});

DEMO:http://jsfiddle.net/VzVy6/8/

演示:http : //jsfiddle.net/VzVy6/8/

The data-dismissattribute on the <a class="close">×</a>actually removes the Alert when clicked, so you can't show it again later. So instead of using that attribute, you can do what you want by manually hiding/showing the specific Alert associated with the class="close"elements.

上的data-dismiss属性在<a class="close">×</a>单击时实际上会删除警报,因此您以后无法再次显示它。因此,您可以通过手动隐藏/显示与class="close"元素关联的特定警报来执行您想要的操作,而不是使用该属性。