问题
How could I check a textbox before submition?
<form action='search.php' method='GET'>
<input type="text" id= "q" name="q" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>
回答1:
Try this simple with JavaScript validation:
<html>
<head>
<script type="text/javascript">
function check()
{
var searchtext = document.getElementById("q").value;
if(searchtext=='')
{
alert('Enter any character');
return false;
}
}
</script>
</head>
<body>
<form action='search.php' method='GET' onSubmit="return check();">
<input type="text" id= "q" name="q" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>
</body>
</html>
回答2:
<?php
if(!empty($_GET['q']))
{
//if it is not empty, do something
}
else
{
//otherwise do this
}
?>
May I also recommend using POST rather than GET if you're sending something from a form.
回答3:
You can use jQuery as in the following:
$(function(){
$('#submit').click(function(e){
if($('#q').val() != null && $('#q').val().length > 0){
$.get('search.php', $('#formId').serialize(), function(result){});
}
else{
//Otherwise do this
}
e.preventDefault();
});
});
回答4:
You can use some stylish jQuery library for easy coding like jQuery validation plugin.
来源:https://stackoverflow.com/questions/15997632/check-textbox-before-submitting