Check textbox before submitting

我们两清 提交于 2020-01-15 03:46:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!