Forms jQuery Mobile无法阻止提交空输入字段值
在我用jQuery Mobile v1.4.5和jQuery 1.12.0构建的网站上,我有一个表单输入字段,用户可以使用返回键(没有明确的提交按钮)提交消息。我想防止用户提交空输入,我基本上在这里找到了Stackoveflow和重用代码,但不知何故它仍然失败,这意味着我的函数仍然传递空输入值 这里的任何人都能发现我的代码中关于为什么提交空输入字段仍然通过验证的问题吗Forms jQuery Mobile无法阻止提交空输入字段值,forms,validation,jquery-mobile,form-submit,trim,Forms,Validation,Jquery Mobile,Form Submit,Trim,在我用jQuery Mobile v1.4.5和jQuery 1.12.0构建的网站上,我有一个表单输入字段,用户可以使用返回键(没有明确的提交按钮)提交消息。我想防止用户提交空输入,我基本上在这里找到了Stackoveflow和重用代码,但不知何故它仍然失败,这意味着我的函数仍然传递空输入值 这里的任何人都能发现我的代码中关于为什么提交空输入字段仍然通过验证的问题吗 <form id="formNewMessage" data-ajax="true" method="post" acti
<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>
$('#messageInput')。按键(功能(e){
如果((e.which==13)和($.trim($('#messageInput').val()!=“”){//send message on Return,但阻止空提交最有可能是它选择回车键,因此它认为输入不是空的
替换这个
$('#messageInput').val()) != ""
与
获取长度(输入中的字符数)并检查其是否大于1。将此($('#messageInput').val())!=“”)替换为此($('#messageInput').val()).length>1),以获取长度(输入中的字符数)并检查其是否大于1。此时它看起来像是将enter键作为一个字符拾取,可能是一个新行。如果它不起作用,请尝试>2,因为我认为新行实际上是2个字符,例如(/n)@太棒了,谢谢你,它使用.length>1
工作!我曾经在代码中有过这个,但我不记得为什么我更改了它…你想把你的回答作为我问题的答案发布吗?好的,我会发布一个答案
$('#messageInput').val()).length > 1