使用 .submit() 处理程序
<div id="searchbar">
<form method='GET' action='search.php' id='formdata'>
<input type="text" placeholder="Search Database" name="searchkey" id="searchkey" />
<input type="submit" value="search" id="search">
</form>
</div>
$(document).ready(function()
$( "#formdata" ).submit(function( event ) {
//alert( "Handler for .submit() called." );
if($('#searchkey').val() === ''){
event.preventDefault();
}
else {
alert($('#searchkey').val());
}
});
});
我在第二个答案中包含了一个额外的提交按钮
<div id="searchbar">
<form method='GET' action='search.php'>
<input type="text" placeholder="Search Database" name="searchkey" id="searchkey" />
<input type="submit" value="search" id="search">
</form>
</div>
<script type="text/javascript" src="script/jquery.js"></script> //include jquery.js
<script type="text/javascript">
$(document).ready(function(){
$('#search').on('click',function(){
if($.trim($('#searchkey')).val() == '')
{
alert("No search Keyword");
return false;
}
else {
alert("search Keyword");
return true;
}
})
});
</script>
我使用 trim() 函数删除搜索字符串开头和结尾的空格
<div id="searchbar">
<form method='GET' action='search.php' id='formdata'>
<input type="text" placeholder="Search Database" name="searchkey" id="searchkey" />
<input type="submit" value="search" id="search">
</form>
</div>
<script type="text/javascript" src="script/jquery.js"></script> //include jquery.js
<script type="text/javascript">
$(document).ready(function(){
$('#formdata').submit(function(){
if($.trim($('#searchkey').val()) == '')
{
alert("No search Keyword");
return false;
}
else
{
alert($('#searchkey').val());
return true;
}
})
});
</script>