HTML - 必需的文本框和提交按钮

时间:2014-09-19 21:17:38

标签: html html5 button textbox onclick

<label for="first_name">First Name</label> 
<input name="FirstName" type="text" id="first_name" required/> 
<input type="submit"/> 

上面的代码显示了一个文本框和一个提交按钮。文本框不能留空,否则会显示一条消息&#34;请填写此字段&#34;单击提交按钮后。

我的问题是如何将onclick属性与提交按钮合并?

所以,如果文本框不是空白,并且按下了提交按钮,我希望它执行一个类似于 - &gt; onclick="postNameToDatabase()"的功能(同时仍然保持空白字段)消息功能)。

已编辑:我已尝试过此操作:<input type="submit" onclick="postNameToDatabase()"/>但即使单击按钮时文本框为空,该功能仍会执行。

3 个答案:

答案 0 :(得分:0)

你可以用jQuery做这样的事情:

$('form').submit(function() {
    if($('input[type=text]').val() == '') {
        return false;
        //Display error message
    } else {
        return true;
    }
});

答案 1 :(得分:0)

PHP答案

您需要使用服务器端语言连接到数据库,这样做的好处是更安全,因为您的凭据没有显示在源代码中供人们窃取,以及如果您的浏览器将如何连接不允许使用javascript吗?

您需要添加数据库名称,表格,用户名和密码。

使用此代码

&#13;
&#13;
   <form action=""method="post">
    	  <label>First Name</label>
    	  <input type="text" name="FirstName" />
    	  <input type="submit" value="Submit" />
    
    
    <?php
    
    //add address of database, username and password
    $con = mysql_connect("localhost","Username","password") or die('I cannot connect to the database  because: ' . mysql_error());
                  
                  //-select  the database to use, add database name
                  $mydb = mysql_select_db("yourdatabase") or die(mysql_error());

    			  //add the table in your db
    			 $strSQL = sprintf("INSERT INTO yourtable (FirstName) VALUES ('%s')", 
          @mysql_real_escape_string($_POST["FirstName"]),
         
    			  // The SQL statement is executed 
    	mysql_query($strSQL) or die (mysql_error());
    
    	// Close the database connection
    	mysql_close();
    	
    
    
    
    ?>
    
    
      </form>
&#13;
&#13;
&#13;    

答案 2 :(得分:0)

只需获取文本框的值并将其检查为空。如果是空的则抛出错误

throw {name:'Error',message:'Fill textbox'};

相关问题