如何在HTML表单中输入文本后显示按钮


How do I make a button appear after inputting text in an HTML form?

我正在编写一个HTML表单,在这里我实现了一个反垃圾邮件系统,生成两个随机数,并要求用户将总和输入到文本字段中。如果答案是正确的,则会出现"提交"按钮,用户可以继续操作。如果答案不正确,则会收到一条通知,上面写着"答案不正确"。HTML表单本身在一个表中。在最后一行单元格中,我将以下代码放入:

<td>
<?php 
$firstnumber = rand(0, 5);
$secondnumber = rand(0,6);
echo 'Anti-spam: '.$firstnumber.' + '.$secondnumber.' = ?</td><td><input name="human" placeholder = "Do the math">'; 
?>
</td>
<tr>
<td colspan="2">
By submitting this form you are agreeing to the <a href="http://http://j2partners.net/index.php?site=tos" target="_blank">terms of service and agreements.</a><br><br>
<?php 
$answer = $_POST['human'];
if($answer == $firstnumber + $secondnumber) {
echo '<input id="submit" name="submit" type="submit" value="I Agree"> <input id="reset" name="reset" type="reset" value="Reset">'; } 
else {
echo '<font color=#ea596c>Incorrect answer</font>';
?>
</td>

但是,当答案输入框中时,"提交"按钮不会重新出现:(

选项1(不太安全)添加具有正确答案的隐藏输入

<input type="hidden" name="answerswer" value="<?=$firstnumber+$secondnumber;?"/>

并在提交后检查数据

if($_POST["anwer"]==$_POST["human"]) ...

选项2使用SESSION记住正确答案。如果要执行服务器端检查,则必须显示提交按钮-数据必须发送到服务器。要显示/隐藏提交按钮,必须执行客户端检查并使用javascript,请参阅选项3。

<?
  session_start(); // necessary to use session vars
  $firstnumber = rand(0, 5);
  $secondnumber = rand(0, 6);
  if(!empty($_SESSION["answerswer"]) && $_SESSION["answerswer"]==@$_POST["human"]) {
    // the math was ok
  }
  $_SESSION["answerswer"] = $firstnumber + $secondnumber; // must be AFTER the check
?>
<form method="post">
  <?="$firstnumber + $secondnumber = ";?>
  <input name="human" type="text" placeholder="do the math"/>
  <input type="submit"/> <!-- can't be hidden without javascript -->
</form>

选项3客户端javascript解决方案,类似vasiljevski的东西推荐

<span id="first"></span> + <span id="first"></span>
<input oninput="check(this)" placeholder="do the math"/>
<input type="submit" id="submit" style="display: none"/>
<script>
  var first=Math.floor(Math.random()*10);
  var second=Math.floor(Math.random()*10);
  var gid = document.getElementById.bind(document);
  gid("first").innerHTML = first;
  gid("second").innerHTML = second;
  function check(input) {
    gid("submit").style.display = input.value==first+second ? "inline" : "none";
  }
</script>

您需要在表单中添加一些JavaScript来实现这一点。在输入时添加按键事件,并检查输入是否有效。

<input id="antispam" name="human" onkeyup="checkEntry" placeholder = "Do the math">'; 
?>
<script>
function checkEntry()
{
var x=document.getElementById("antispam");
if (x=={correct answare})
  {
    [add submite button]
  }
else
{
   [add incorrect text]
}
</script>

每次加载页面时都会生成新的随机数。因此,当用户进行计算并提交表单时,会出现一个新的请求,而您的随机数是新生成的,因此计算无法匹配(随机情况下可能是相同的结果)。

您必须将数学结果存储在会话或隐藏的输入字段(编码或其他)中,以便在提交表单后知道结果。

或者你想在JavaScript中检查结果以显示按钮,但我不会对客户端进行人性化检查。