【问题标题】:How prevent submit if input are empty with javascript如果使用javascript输入为空,如何防止提交
【发布时间】:2012-05-09 12:29:48
【问题描述】:

我有一个登录表单,但我想检查字段是否为空,然后不要提交。我在提交时做了'return false',但浏览器仍然加载一个新页面。我怎样才能阻止它?

JS:

var username = document.getElementById('usernameField');
    var password = document.getElementById('passwordField');
    var loginBtn = document.getElementById('loginBtn');
    var infoBox = document.getElementById('formInfo');

    var isEmpty = /^\s*$/;

    var addEventTo = function(id, type, fn, capture) {
        if (document.addEventListener) {
            id.addEventListener(type, fn, capture);
        } else {
            id.attachEvent('on'+type, fn);
        }
    };

    function checkIfAllEmpty() {
        var loginForm = document.getElementById('loginform'),
            allInputs = loginForm.getElementsByTagName('input'),
            max = allInputs.length,
            i;

            for (i = 0; i < max; i++) {
                if (allInputs[i].type !== 'submit') {

                    if (allInputs[i].match(isEmpty)) {
                        infoBox.innerHTML = 'All your fields are empty';
                        return false;
                    }
            }
        }
    }

    //addEventTo(loginBtn, 'click', checkIfAllEmpty, false);

    if (document.addEventListener) {
            loginBtn.addEventListener('submit', checkIfAllEmpty, false);
    } else {
            loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
    }

HTML:

<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
    <fieldset id="loginFieldset">
        <legend>Sign in</legend>
        <ol>
            <li>
                <label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
                <span>Please type in your username</span>
            </li>
            <li>
                <label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
                <span>Please type your password</span>
            </li>
            <li>
                <input type="submit" value="Sign in" id="loginBtn" />
            </li>
        </ol>
    </fieldset>
</form>

非常感谢

【问题讨论】:

  • 能否提供表单的 HTML 代码?还是动态创建表单?
  • 嗨@Naama Katiee:我已经添加了HTML...

标签: javascript validation


【解决方案1】:

如果可以使用 html5(适用于较新版本的 Safari、Chrome、Firefox、Opera > 11.00 但没有像往常一样的 IE),您可以在输入字段中添加所需的标签。

<p id="formInfo"></p>
  <form id="loginForm" method="post" action="#">
    <fieldset id="loginFieldset">
      <legend>Sign in</legend>
      <ol>
        <li>
         <label for="usernameField">Username</label>
         <input type="text" placeholder="Enter username" id="usernameField" required />
         <span>Please type in your username</span>
        </li>
        <li>
         <label for="passwordField">Password</label>
         <input type="password" placeholder="Enter password" id="passwordField" required />
         <span>Please type your password</span>
        </li>
        <li>
            <input type="submit" value="Sign in" id="loginBtn" />
        </li>
    </ol>
</fieldset>

【讨论】:

  • 只输入空格怎么样?我刚刚使用了这个,但是在输入字段中输入空格时它仍然提交。
【解决方案2】:

看起来 onsubmit 的事件监听器没有被正确添加,无论如何最简单的方法是在你的表单中添加 onsubmit="return someValidationFuncThatReturnTrueOrFalse()" :

<form id="loginForm" method="post" action="#" onsubmit="return validate()">

我能问一下你为什么在你的 js 代码中使用这种方法吗?如果您的表单是静态的,则可以轻松完成...

function validate() {
    if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
         alert("all fields are empty");
         return false;
    } else {
        return true;
    }
}

或类似的东西......

【讨论】:

  • 但是我不能为此使用任何库,它必须是纯 javascript
【解决方案3】:

您可以对表单输入使用属性 disabled="disabled" :

http://www.w3schools.com/tags/att_input_disabled.asp

将提交按钮设置为禁用,然后为每个输入字段添加一个 onchange 侦听器,这样如果每个字段都已填写,则删除禁用属性,用户可以提交表单。

【讨论】:

    【解决方案4】:

    我使用 Prototype(作为 javascript 框架),这段代码应该可以工作:

    js:

    function checkEmpties() {
        var usr = $('username');
        var pass = $('pass');
        var frm = $('formId');
    
    
        if (usr.value && pass.value) {
            //frm.submit();
            alert('submit');
        } else {
            alert('failed');
        }
    }
    
    Event.observe(window, 'DomReady', function() {
        var btn = $('submitBtn');
        Event.observe('submitBtn', 'click', checkEmpties);
    }
    

    html:

    <form id="formId">
        <input type="text" name="username" id="username" />
        <input type="password" name="pass" id="pass" />
        <input type="button" id="submitBtn" value="Send"  />
    </form>
    

    它的作用: 一旦文档加载完毕,就会给按钮附加一个事件观察器,所以当它被点击时,函数 checkEmpties 就会被调用。 此函数将检索输入的值,如果它们不为空,则提交表单。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2011-12-23
      • 1970-01-01
      • 2017-11-18
      • 2013-07-25
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多