javascript – Dynamický formulář – appendChild(), removeChild()

Od posmura

 

<?php
echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>Dynamický formulář</title>
</head>
<body>
HTML;
echo <<<FORM
<h1>Dynamický formulář</h1>
<form id="formular" name="formular" action="vp_dynamicky_formular.php" method="post" accept-charset="utf-8">
<input type="text" id="pevny_input_text" name="pevny_input_text" value="Toto je hodnota pevny_input_text." />
<input type="hidden" id="pevny_input_hidden" name="pevny_input_hidden" value="Toto je hodnota pevny_input_hidden." />
<input type="button" id="tlacitko_vytvorit_pole" name="tlacitko_vytvorit_pole" value="Vytvořit pole" onclick="VytvoritPole();" />
<input type="button" id="tlacitko_obebrat_pole" name="tlacitko_obebrat_pole" value="Odebrat pole" onclick="OdstraniPosledniPole();" />
<input type="submit" id="tlacitko_odeslat" name="tlacitko_odeslat" value="Odeslat" />
</form>
FORM;
echo <<<JS
<script>
var DYNAMICKE_POLE_PORADI = 0;
function VytvoritPole() {
  alert ("Vytvářím dynamicky vytvořené pole " + DYNAMICKE_POLE_PORADI + "...");
  var input = document.createElement('input');
  input.setAttribute("name", "dynamicky_vytvorene_pole_" + DYNAMICKE_POLE_PORADI);
  input.setAttribute("id", "dynamicky_vytvorene_pole_" + DYNAMICKE_POLE_PORADI);
  input.setAttribute("value", "Toto je hodnota dynamicky_vytvorene_pole_" + DYNAMICKE_POLE_PORADI + ".");
  input.setAttribute("type", "text");
  var form = document.getElementById("formular");
  form.appendChild(input);
  DYNAMICKE_POLE_PORADI ++;
}
function OdstraniPosledniPole() {
  DYNAMICKE_POLE_PORADI --;
  alert ("Odstraňuji dynamicky vytvořené pole " + DYNAMICKE_POLE_PORADI + "...");
  var input = document.getElementById("dynamicky_vytvorene_pole_" + DYNAMICKE_POLE_PORADI);
  input.parentNode.removeChild(input);
}
</script>
JS;
if (isset($_POST["pevny_input_text"]) and strlen ($_POST["pevny_input_text"]) > 0) {
  echo "<h2>Seznam předaných hodnot \$_POST</h2><ol>";
  foreach ($_POST as $index => $hodnota) {
    echo "<li>{$index} => {$hodnota}</li>";
  }
  echo "</ol>";
}
echo <<<HTML
</body>
</html>
HTML;
?>