繁体   English   中英

试图防止使用javascript在textarea中发布空值

[英]Trying to prevent posting empty value in a textarea using javascript

我有一个简单的应用程序,可在输入键盘输入命令时从文本区域提交该文件。 我正在尝试阻止用户使用javascript将空数据提交到表单,这是我的尝试,但是我的挑战是它正在提交要按Enter键盘

document.getElementById('new-input').addEventListener('keyup', function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13 && $(this).val().length > 0) { // enter key press     && $(this).val().length > 0
        e.preventDefault();
        send();
    }
});

这是发送方法

function send() {
        var message = document.getElementById('new-input').value.trim(),
                xhr = new XMLHttpRequest();
       // alert('first message>>>>> '+message);

        xhr.onload = function (response) {
            if (xhr.status === 200) {
                document.getElementById('new-input').value = '';

            } else {
                alert('Request failed.  Returned status of ' + xhr.status);
                location.href = '/';
            }
        };
        xhr.send(encodeURI('message=' + message));

    }

请如何防止用户提交空值。 使用angularjs或javascript

您可以使用$ .trim来检查空格:

if ( code == 13 && $.trim($(this).val()) )

如果不为空,将返回true。

暂无
暂无

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

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