PHP Form TextField

In this chapter you will learn:

  1. What is PHP Form TextField
  2. Value attribute
  3. Example - Read value from text field
  4. Example - A PHP Number Guessing Script

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>/* java 2 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/*j  a  v  a 2 s  .  co  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>

Next chapter...

What you will learn in the next chapter:

  1. What is password field
Home » PHP Tutorial » PHP Form
PHP HTML Forms
PHP GET and POST
PHP Form Elements
PHP Form TextField
PHP Form Password Field
PHP Form Textarea
PHP Form CheckBox
PHP Form Select
PHP Form RadioButton
PHP Form Submit
PHP Form Reset
PHP Form Push Button
PHP Form Image
PHP Form Hidden Field
PHP Split Form Across Pages
PHP Form Validation
PHP Form File Upload
PHP Form Demo
PHP Form Empty Fields
PHP Form Multi-Value Fields
PHP Redirect after a Form Submission