所以我有一个带有一类搜索的提交按钮,当点击时,一个searchBar类的输入值为空,然后searchBar显示:block并且不提交表单。但是我希望能够关闭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 :(得分:1)
如果我对问题的理解是正确的,您可以切换搜索框的显示以达到您的需要
$('.searchBar').css('display', 'block'); // instead of this
$('.searchBar').toggle(); // put this
答案 1 :(得分: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>
答案 2 :(得分: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;
}
});