简体   繁体   English

搜索字段为空时如何防止提交搜索表单?

[英]How to prevent submitting search form when search field is empty?

Here the code below disables search button when search box is empty. 如果搜索框为空,则下面的代码将禁用搜索按钮。 When input type for search button is set to submit then neither submit nor the enter key from keyboard submits empty form but when I change input type to button and put the cursor inside input field and press enter button even empty form is posted causing reloading of page. 当将搜索按钮的输入类型设置为submit则既不提交也不输入键盘上的Enter键,而是提交空白表格,但是当我将输入类型更改为button并将光标置于输入字段中并按Enter按钮时,即使张贴了空白表格也导致重新加载页面。 How to prevent submitting search form on pressing enter when search field is empty? 当搜索字段为空时,如何防止在按Enter键时提交搜索表单?

<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form> 

<script>
$(document).ready(function(){
$('.Button').attr('disabled',true);
$('.search').keyup(function(){
if($(this).val().length !=0)
    $('.Button').attr('disabled', false);            
else
    $('.Button').attr('disabled',true);
 })
});
</script>

Add a event listener for the form submission 为表单提交添加事件监听器

$('form').submit(function(e){
    // check logic here
    if ($('.search').val().length < 1)
       e.preventDefault()
});

where e.preventDefault will avoid the form being submitted if no value 如果没有值,则e.preventDefault将避免提交表单

otherwise the form will submitted normally 否则,表格将正常提交

You can try like this 你可以这样尝试

$('form').submit(function(e){
    if ($('.search').val().length<=0)
        return false;
});

here is your code with some modification: 这是经过一些修改的代码:

JsFiddle Demo JsFiddle演示

 $(document).ready(function(){ // By default submit is disabled $('.Button').prop('disabled', true); $('.search').keyup(function() { if($(this).val().length !=0 ) { $('.Button').prop('disabled', false); } else { $( ".search").focus(); $('.Button').prop('disabled', true); e.preventDefault(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form action="search.php" method="post"> <input type="text" class="search" placeholder="search here"/> <input type="submit" class="Button" value="search"/> </form> 

JsFiddle Demo JsFiddle演示

you should use prop instead of attr if you want to change disabled 如果要更改disabled则应使用prop而不是attr

$(function() {
  $('.Button').prop('disabled', true);
  $('.search').keyup(function() {
    $('.Button').prop('disabled', !$(this).val());
  });
});

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

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