PHP Form TextField

Description

A text input field allows the user to enter a single line of text.

Value attribute

You can optionally prefill the field with an initial value using the value attribute . To leave it blank, specify an empty string for the value attribute, or leave the attribute out altogether.


<label for="textField">A text input field</label> 
<input type="text" name="textField" id="textField" value="" /> 

Example 1

The following code is for index.htm file and it has a text field and submit button.


<html>//from  ww w.j  a  v a2 s  . c o m
<body>
   <form action="index.php" method="get">
      <input type="text" name="user" />
      <input type="submit" value="hit it!" />
    </form>
</body>
</html>

Name the following script as index.php and put it into the same folder as above index.htm file. It accepts the value from the text field by using field name user.


<?php
  print "Welcome <b>" . $_GET ['user'] . "</b><br/>";
?>

Example 2

A PHP Number Guessing Script


<?php// w ww.  j  a  va2s. c o  m
$num_to_guess = 42;
$message = "";
if ( ! isset( $_POST['guess'] ) ) {
   $message = "Welcome!";
} else if ( $_POST['guess'] > $num_to_guess ) {
   $message = $_POST['guess']." is too big!";
} else if ( $_POST['guess'] < $num_to_guess ) {
   $message = $_POST['guess']." is too small!";
} else { 
   $message = "Well done!";
}
?>
<html>
<body>
  <h1> 
     <?php print $message ?> 
  </h1>
  <form method="post" action="<?php print $_SERVER['PHP_SELF']?>">
  <p>
     Type your guess here: 
     <input type="text" name="guess" />
     <input type="submit" value="submit" />
  </p>
  </form>
</body>
</html>

The code above generates the following result.

PHP Form TextField




















Home »
  PHP Tutorial »
    Form »




PHP Form
Form Demo