jQuery Mobile无法阻止提交空输入字段值

时间:2016-01-20 22:29:21

标签: forms validation jquery-mobile form-submit trim

在我使用jQuery Mobile v1.4.5和jQuery 1.12.0构建的网站上,我有一个表单输入字段,用户可以使用Return键提交消息(没有显式提交按钮)。我想阻止用户提交空输入,我基本上在Stackoveflow上找到了solutions for that并重用了代码,但不知怎的它仍然失败,这意味着我的功能仍传递空输入值。

这里的任何人都可以通过我的代码发现有关为什么提交空输入字段仍然通过验证的问题吗?

<form id="formNewMessage" data-ajax="true" method="post" action="ajax_post_message.php">
    <input type="hidden" name="fromMobile" id="fromMobile" value="1">
    <input type="text" name="messageInput" id="messageInput" data-clear-btn="true" placeholder="Type your message here..." autocomplete="off">
</form>
<script>
$('#messageInput').keypress(function(e){
    if ((e.which == 13) && ($.trim($('#messageInput').val()) != "")) { // send message on Return, but prevent empty submits <-- this is not working :(
        $(this).attr('disabled', 'disabled'); // lock the input field
        $('#formNewMessage').submit(function(ev){
            $.ajax({
                type: $('#formNewMessage').attr('method'),
                url: $('#formNewMessage').attr('action'),
                data: $('#formNewMessage').serialize(),
                success: function (data) {
                    $('#messageInput').val(''); // clear the input field
                    window.location.reload(true); // reload the page
                },
                error: function(jqXHR, textStatus, errorThrown) {
                   alert(textStatus + ' ' + errorThrown);
                }
            });
            ev.preventDefault(); // avoid to execute the actual submit of the form.
        });
        $(this).removeAttr('disabled'); // unlock the input field
    }
});
</script>

感谢您解决此问题的任何提示和窍门!

1 个答案:

答案 0 :(得分:1)

很可能它选择Enter作为键,因此它认为输入不是空的

替换此

$('#messageInput').val()) != ""

$('#messageInput').val()).length > 1

获取长度(输入中没有字符)并检查其是否大于1。

相关问题