2016-09-01 33 views
0

所以我有一個提交按鈕,帶有一個搜索類,當點擊並且一個searchBar類的輸入值爲空時,searchBar顯示:block and doesn'提交表格。然而,我希望能夠關閉searchBar,如果該值仍然是空的,但提交(搜索)被再次點擊。如果點擊提交,我該如何關閉輸入

$('#form').submit(function() { 
if ($.trim($(".searchBar").val()) === "") { 
    $('.searchBar').css('display', 'block'); 
    return false; 
} else { 
    return true; 
} 
}); 

HTML:

<form id="form" action=""> 
    <input value="" type="text" placeholder="Product name or ID" name="search" class="searchBar" /> 
    <input type="submit" readonly="readonly" class="search" /> 
</form> 

CSS:

#form .searchBar { 
    display: none; 
} 
+0

對不起,我認爲你沒有提供足夠的信息給某人t o能夠幫助你。用html完成的演示將有很大幫助。 – Moritur

+0

@Moritur添加了html。 –

回答

1

如果我的問題的理解是正確的,你可以切換搜索框的顯示,以達到你所需要的

$('.searchBar').css('display', 'block'); // instead of this 


$('.searchBar').toggle(); // put this 
+0

是的!非常感謝! –

+0

有幫助的答案。 。 –

0

根據您的代碼我已經做了這樣的事情

$('#form').submit(function() { 
 
       if ($.trim($(".searchBar").val()) === "") { 
 
        $('.searchBar').show(); 
 
        return false; 
 
       } else { 
 
        return true; 
 
       } 
 
      });
#form #search { 
 
       display: none; 
 
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form id="form" action="" method="post"> 
 
      <input value="" type="text" placeholder="Product name or ID" name="search" id="search" value="testValue" class="searchBar" /> 
 
      <input type="submit" readonly="readonly" class="search" /> 
 
     </form>

您可以檢查這個例子中,如果你喜歡

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <title>Example</title> 
     <meta charset="utf-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>   
     <style> 
      #form #search { 
       display: none; 
      } 
     </style> 
    </head> 
    <body> 
     <form id="form" action="" method="post"> 
      <input value="" type="text" placeholder="Product name or ID" name="search" id="search" value="testValue" class="searchBar" /> 
      <input type="submit" readonly="readonly" class="search" /> 
     </form> 
     <script> 

      $('#form').submit(function() { 
       if ($.trim($(".searchBar").val()) === "") { 
        $('.searchBar').show(); 
        return false; 
       } else { 
        return true; 
       } 
      }); 
     </script> 
    </body> 
</html> 
0

如果我的理解對不對,你可以試試這段代碼:

var countClick=0; 
$('#form').submit(function() { 
    countClick++; 
    if ($.trim($(".searchBar").val()) === "") 
    {  
     if(countClick==1) 
     { 
      $('.searchBar').css('display', 'block'); 
      return false; 
     } 
     else 
     { 
      $('.searchBar').css('display', 'none'); 
      return false; 
     } 
    } 
    else 
    { 
     return true; 
    } 
}); 
相關問題