用于验证表单和显示 css 加载屏幕的 Javascript 函数

标签 javascript css forms validation loading

我是一个 javascript 新手,我正在尝试组合两段单独工作但不能一起工作的代码:

  1. 验证我的表单以检查长度、宽度和高度是否为非零
  2. 如果表单有效,提交表单并在内容加载时显示一个 css 启动加载屏幕

这是我失败的尝试:

<script type = "text/javascript">

function notEmpty(elem, helperMsg){
    if (elem.value.length == 0) {
        alert(helperMsg);
        elem.focus(); // set the focus to this input
        return false;
    }
    return true;
}

function show() {
    if ((notEmpty(document.getElementById('length'), 'Please Enter a Length')==true) &&
        (notEmpty(document.getElementById('height'), 'Please Enter a Height')==true) &&
        (notEmpty(document.getElementById('weight'), 'Please Enter a Weight')==true)) {
        document.getElementById("myDiv").style.display="block";
        setTimeout("hide()", 10000);  // 10 seconds
    }
}
function hide() {
    document.getElementById("myDiv").style.display="none";
}
</script>

我的表单将在表单提交时调用 show()。 myDiv 是一个 css 加载页面元素,它在页面加载时出现。再次,如果我的尝试失败,我深表歉意,我是 javascript 的新手,如果能给我指明正确方向的任何建议,我将不胜感激。

最佳答案

在 HTML 表单中,将 onClick="validate(event)" 添加到提交按钮:

<form action="someAction">
    <input type="text" id="length"/><br/>
    <input type="text" id="height"/><br/>
    <input type="text" id="weight"/><br/>
    <input type="submit" onClick="validate(event)"/>
</form>
<div id="myDiv" style="display: none">Loading....</div>

然后试试这个代码:

function validate(e) {
    (e.preventDefault) ? e.preventDefault() : e.returnValue = false;//stop the form from submitting before validating
    var arr = ['length', 'height', 'weight'],
        valid = true,
        helperMsg = ['please choose length value', 'please choose height value', 'please choose weight vale'];
    for (var i in arr) {
        var elm = document.getElementById(arr[i]);
        if (elm.value.length == 0) {
            alert(helperMsg[i]);
            elm.focus();
            valid = false;            
            break;//stop looping and move to the next step
        }
    }
    if (valid) {
        var div = document.getElementById('myDiv');
        document.getElementsByTagName('form')[0].submit();//submit the first form, or you can change it to document.getElementBY('id') instead if you add an id to your form which would be better.
        div.style.display = 'block';//show div
        setTimeout(function () {
            div.style.display = 'none';//hide div after 10 sec
        }, 10000);
    }

}

DEMO

关于用于验证表单和显示 css 加载屏幕的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15770943/

相关文章:

javascript - webpack - 如何为生产环境和开发环境设置不同的变量

javascript - 异步时 Ember Mocha 测试失败(使用 ember-mocha-adapter)

javascript - 如何从对象数组中获取唯一值

html - 修复移动设备上动画下划线的宽度

jquery - 固定位置在 Chrome 中不起作用

jquery - 'Gravity Forms' 输入按钮被点击时触发jquery

javascript - 如何创建 Javascript 二十一点

css - 摆脱水平框阴影,即使它是 0

ruby-on-rails - rails 4 : new instance creation through form_for not working

javascript - 带有动态输入数量 View 的 ASP.NET MVC