Table of Contents

Web Developent Lesson 8 - Forms

Javascript

Objectives

In this activity you'll learn to use Javascript to

Setup

form.php

<?php
    include('database.php');

    include('header.php');
    include('menu.php');

    // get list of heroes
    $query = "SELECT * FROM heroes";
    $args  = array();
    $hrslt = $pdo->prepare($query);
    $hrslt->execute($args);

    // get list of movies
    $query = "SELECT movie FROM appearances GROUP BY movie";
    $args  = array();
    $mrslt = $pdo->prepare($query);
    $mrslt->execute($args);
?>
    <main>
        <form name="add_hero" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Hero</legend>
                <ul>
                    <li>
                        <label>Alias:</label>
                        <input type="text" name="alias" size="30" maxlength="50" hint="Iron Man">
                    </li>
                    <li>
                        <label>Identity:</label>
                        <input type="text" name="identity" size="30" maxlength="50" hint="Tony Stark">
                    </li>
                    <li>
                        <label>Side:</label>
                        <ul>
                            <li><input type="radio" name="side" value="Hero" checked> Hero</li>
                            <li><input type="radio" name="side" value="Villain"> Villain</li>
                        </ul>
                    </li>
                    <li>
                        <label>First Appearance:</label>
                        <input type="number" name="year">
                    </li>
                    <li>
                        <label>Source of Power:</label>
                        <select name="power">
                            <option value="Skill">Skill</option>
                            <option value="Biological">Biological</option>
                            <option value="Magic">Magic</option>
                            <option value="Technology">Technology</option>
                            <option value="Mutant">Mutant</option>
                        </select>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add / Update Hero">
            </fieldset>
        </form>

        <form name="add_appearances" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Appearances</legend>
                <ul>
                    <li>
                        <label>Hero</label>
                        <select name="alias">
<?php
    // display list of heroes
    while($row = $hrslt->fetch()) {
?>
                            <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option>
<?php
    }
?>
                        </select>
                    </li>
                    <li>
                        <label>Movie</label>
                        <ul>
<?php
    // display list of movies
    while($row = $mrslt->fetch()) {
?>
                            <li><input type="checkbox" name="movie[]" value="<?php echo $row['movie']; ?>" id=""> <?php echo $row['movie']; ?></li>
<?php
    }
?>
                            <li><input type="checkbox" name="movie[]" value="new" id=""> <input type="text" name="new_movie"></li>
                        </ul>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add Appearance">
                <input type="submit" name="submit" value="Delete Appearances">
            </fieldset>
        </form>
    </main>
<?php
    include('footer.php');
?>

process_form.php

<?php
    include('header.php');
    include('menu.php');
    include('database.php');
    
    // check which form
    switch ($_POST['submit']) {
        case 'Add / Update Hero':
            // check whether hero already exists
            $hquery = "SELECT * FROM heroes WHERE alias=?";
            $hargs  = array($_POST['alias']);
            $hrslt  = $pdo->prepare($hquery);
            $hrslt->execute($hargs);
            if($row = $hrslt->fetch()) { // the hero exists
                $query = "UPDATE heroes SET identity=?, hero_villain=?, first_appeared=?, power=? WHERE alias=?";
                $args  = array($_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power'], $_POST['alias']);
                $rslt  = $pdo->prepare($query);
                if($rslt->execute($args)) {
                    $message = "{$_POST['alias']} was updated successfully.";
                } else {
                    $message = "There was a problem updating {$_POST['alias']}.";
                }
            } else {
                $query = "INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)";
                $args  = array($_POST['alias'], $_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power']);
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "{$_POST['alias']} was inserted successfully.";
                } else {
                    $message = "There was a problem inserting {$_POST['alias']}.";
                }
            }
            break;
        case 'Add Appearance':
            $args = array();
            foreach($_POST['movie'] as $movie) {
                if ($movie == 'new') {
                    array_push($args, $_POST['alias'], $_POST['new_movie']);
                } else {
                    error_log($movie);
                    // check if it exists already
                    $mquery = "SELECT * FROM appearances WHERE alias=? AND movie=?";
                    $margs  = array($_POST['alias'], $movie);
                    $rslt   = $pdo->prepare($mquery);
                    $rslt->execute($margs);
                    if (!$row = $rslt->fetch()) {
                        array_push($args, $_POST['alias'], $movie);
                    }
                }
            }
            error_log(print_r($args, 1));
            $movies = count($args)/2;
            if ($movies > 0) {
                $values = str_repeat('(?,?), ', $movies-1) . '(?,?)';
                $query = "INSERT INTO appearances (alias, movie) VALUES $values";
                error_log("MURRAY: $query    " . print_r($args, 1));
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "$movies appearances were inserted successfully.";
                } else {
                    $message = "There was a problem inserting $movies appearances.";
                }
            } else {
                $checked = count($_POST['movie']);
                $message = "All $checked appearances are already in the database.";
            }
            
            break;
        case 'Delete Appearances':
            $movies = count($_POST['movie']);
            $values = str_repeat('?,', $movies-1) . '?';
            $query = "DELETE FROM appearances WHERE alias=? AND movie IN ($values)";
            $args  = array($_POST['alias']);
            foreach($_POST['movie'] as $movie) {
                array_push($args, $movie);
            }
            error_log($query . print_r($args, 1));
            $rslt = $pdo->prepare($query);
            if ($rslt->execute($args)) {
                $message = "$movies appearances were deleted successfully.";
            } else {
                $message = "There was a problem deleting $movies appearances";
            }
            break;
        default:
            break;
    }
?>
    <main>
        <p><?php echo $message; ?></p>
    </main>
<?php
    include('footer.php');
?>

style.css

ol {
    color: blue;
  }
  
  ol ol {
    font-weight: 700;
  }

ul {
  list-style-type: none;
}

td, th {
  border-width: 1px;
  border-style: solid;
}

td {
  padding: 10px;
}

table {
  border-collapse: collapse;
}

header {
  background-color:indianred;
  border:darkred solid 2px;
  height: 100px;
  position: absolute;
  left: 16%;
  right: 0px;
  top: 0px;
}

nav {
  background-color: burlywood;
  border:yellow solid 2px;
  position: fixed;
  top: 0px;
  bottom: 0px;
  width: 16%;
  left: 0px;
}

main {
  background-color: lightgree;
  border: darkgreen solid 2px;
  position: absolute;
  top: 100px;
  left: 16%;
  right: 0px;
  bottom: 80px;
  overflow: scroll;
  padding: 20px;
}

footer {
  background-color: lightskyblue;
  border: darkblue solid 2px;
  position: absolute;
  bottom: 0px;
  height: 80px;
  left: 16%;
  right: 0px;
}

.content {
  background-color:coral;
  border:orangered solid 2px;
  height: 400px;
  padding: 40px;
  margin: 20px;
  display: inline-block;
  width: 300px;
}

img {
  float: left;
  max-height: 250px;
  border: solid 2px green;
  margin: 20px 20px 20px 0px;
  padding: 10px;
  border-radius: 30px;
}

#album {
  display: flex;
  justify-content:space-between;
  flex-wrap: wrap;
}

video {
  max-height: 250px;
  float: right;
  clear: left;
  margin: 20px 0px 20px 20px;
  padding: 10px;
}

audio {
  margin: 20px 20px 20px 0px;
  padding: 10px 10px 10px 0px;
}

input[type=button] {
  display: block;
}

figcaption {
  display: block;
  text-align: center;
  font-family: 'Arial', sans-serif;
  color: green;
}

label {
  display: inline-block;
  width: 10em;
  text-align: right;
}

input[type=checkbox], input[type=radio] {
  margin-left: 11em;
}

input[type=text], input[type=number], select {
  margin-left: 1em;
}

input[name=new_movie] {
  margin-left: 0em;
}

Single Page Form and Processing

<?php
    include('database.php');
    // check which form
    switch ($_POST['submit']) {
        case 'Add / Update Hero':
            // check whether hero already exists
            $hquery = "SELECT * FROM heroes WHERE alias=?";
            $hargs  = array($_POST['alias']);
            $hrslt  = $pdo->prepare($hquery);
            $hrslt->execute($hargs);
            if($row = $hrslt->fetch()) { // the hero exists
                $query = "UPDATE heroes SET identity=?, hero_villain=?, first_appeared=?, power=? WHERE alias=?";
                $args  = array($_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power'], $_POST['alias']);
                $rslt  = $pdo->prepare($query);
                if($rslt->execute($args)) {
                    $message = "{$_POST['alias']} was updated successfully.";
                } else {
                    $message = "There was a problem updating {$_POST['alias']}.";
                }
            } else {
                $query = "INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)";
                $args  = array($_POST['alias'], $_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power']);
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "{$_POST['alias']} was inserted successfully.";
                } else {
                    $message = "There was a problem inserting {$_POST['alias']}.";
                }
            }
            break;
        case 'Add Appearance':
            $args = array();
            foreach($_POST['movie'] as $movie) {
                if ($movie == 'new') {
                    array_push($args, $_POST['alias'], $_POST['new_movie']);
                } else {
                    error_log($movie);
                    // check if it exists already
                    $mquery = "SELECT * FROM appearances WHERE alias=? AND movie=?";
                    $margs  = array($_POST['alias'], $movie);
                    $rslt   = $pdo->prepare($mquery);
                    $rslt->execute($margs);
                    if (!$row = $rslt->fetch()) {
                        array_push($args, $_POST['alias'], $movie);
                    }
                }
            }
            error_log(print_r($args, 1));
            $movies = count($args)/2;
            if ($movies > 0) {
                $values = str_repeat('(?,?), ', $movies-1) . '(?,?)';
                $query = "INSERT INTO appearances (alias, movie) VALUES $values";
                error_log("MURRAY: $query    " . print_r($args, 1));
                $rslt  = $pdo->prepare($query);
                if ($rslt->execute($args)) {
                    $message = "$movies appearances were inserted successfully.";
                } else {
                    $message = "There was a problem inserting $movies appearances.";
                }
            } else {
                $checked = count($_POST['movie']);
                $message = "All $checked appearances are already in the database.";
            }
            
            break;
        case 'Delete Appearances':
            $movies = count($_POST['movie']);
            $values = str_repeat('?,', $movies-1) . '?';
            $query = "DELETE FROM appearances WHERE alias=? AND movie IN ($values)";
            $args  = array($_POST['alias']);
            foreach($_POST['movie'] as $movie) {
                array_push($args, $movie);
            }
            error_log($query . print_r($args, 1));
            $rslt = $pdo->prepare($query);
            if ($rslt->execute($args)) {
                $message = "$movies appearances were deleted successfully.";
            } else {
                $message = "There was a problem deleting $movies appearances";
            }
            break;
        default:
            break;
    }

    include('header.php');
    include('menu.php');

    // get list of heroes
    $query = "SELECT * FROM heroes";
    $args  = array();
    $hrslt = $pdo->prepare($query);
    $hrslt->execute($args);

    // get list of movies
    $query = "SELECT movie FROM appearances GROUP BY movie";
    $args  = array();
    $mrslt = $pdo->prepare($query);
    $mrslt->execute($args);
?>
    <main>
        <form name="add_hero" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Hero</legend>
                <ul>
                    <li>
                        <label>Alias:</label>
                        <input type="text" name="alias" size="30" maxlength="50" hint="Iron Man">
                    </li>
                    <li>
                        <label>Identity:</label>
                        <input type="text" name="identity" size="30" maxlength="50" hint="Tony Stark">
                    </li>
                    <li>
                        <label>Side:</label>
                        <ul>
                            <li><input type="radio" name="side" value="Hero" checked> Hero</li>
                            <li><input type="radio" name="side" value="Villain"> Villain</li>
                        </ul>
                    </li>
                    <li>
                        <label>First Appearance:</label>
                        <input type="number" name="year">
                    </li>
                    <li>
                        <label>Source of Power:</label>
                        <select name="power">
                            <option value="Skill">Skill</option>
                            <option value="Biological">Biological</option>
                            <option value="Magic">Magic</option>
                            <option value="Technology">Technology</option>
                            <option value="Mutant">Mutant</option>
                        </select>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add / Update Hero">
            </fieldset>
        </form>

        <form name="add_appearances" action="process_form.php" method="post">
            <fieldset>
                <legend>Add Appearances</legend>
                <ul>
                    <li>
                        <label>Hero</label>
                        <select name="alias">
<?php
    // display list of heroes
    while($row = $hrslt->fetch()) {
?>
                            <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option>
<?php
    }
?>
                        </select>
                    </li>
                    <li>
                        <label>Movie</label>
                        <ul>
<?php
    // display list of movies
    while($row = $mrslt->fetch()) {
?>
                            <li><input type="checkbox" name="movie[]" value="<?php echo $row['movie']; ?>" id=""> <?php echo $row['movie']; ?></li>
<?php
    }
?>
                            <li><input type="checkbox" name="movie[]" value="new" id=""> <input type="text" name="new_movie"></li>
                        </ul>
                    </li>
                </ul>
                <input type="submit" name="submit" value="Add Appearance">
                <input type="submit" name="submit" value="Delete Appearances">
            </fieldset>
        </form>
    </main>
<?php
    include('footer.php');
?>
        <form name="add_hero" action="form.php" method="post">
        <form name="add_appearances" action="form.php" method="post">
        <div id="status">
            <p><?php echo $message; ?></p>
        </div>
#status {
  background-color: rgb(238, 157, 157);
  border: darkred 1px solid;
  color: darkred;
  margin-bottom: 20px;
  padding-left: 20px;
}

Timer

    $page = "form";
    include('header.php');
window.onload = function () {
    
}
window.onload = function () {
    var status = document.getElementById('status');
}
    setTimeout(function () {

    }, 10000);
        status.style.display = 'none';
#status {
  background-color: rgb(238, 157, 157);
  border: darkred 1px solid;
  color: darkred;
  margin-bottom: 20px;
  padding-left: 20px;
  display: none;
}
window.onload = function () {
    var status = document.getElementById('status');
    if (status.firstElementChild.innerHTML != '') {
        status.style.display = 'block';
    }
    setTimeout(function () {
        status.style.display = 'none';
    }, 10000);
}

Form Verification

                <input type="button" name="submit" value="Add / Update Hero">
                <input type="button" name="submit" value="Add Appearance">
                <input type="button" name="submit" value="Delete Appearances">
                <input type="button" name="submit" value="Add / Update Hero" onclick="verifyAddHero()">
                <input type="button" name="submit" value="Add Appearance" onclick="verifyAddAppearance()">
                <input type="button" name="submit" value="Delete Appearances" onclick="verifyDeleteAppearance()">

Required Fields

                        <label>Alias:<span class="required">*</span></label>
                        <label>Identity:<span class="required">*</span></label>
                        <label>Side:<span class="required">*</span></label>
                        <label>First Appearance:<span class="required">*</span></label>
                        <label>Source of Power:<span class="required">*</span></label>
.required {
  color: red;
  vertical-align: super;
}
function verifyAddHero() {

}

Text Input

    message = "";
    if (document.getElementsByName('alias')[0].value == "") {
        message += "The alias is required. ";
    }
    console.log(message);
    if (document.getElementsByName('alias')[0].innerHTML == "") {
        message += "The alias is required. ";
    }
    if (document.getElementsByName('identity')[0].innerHTML == "") {
        message += "The identity is required. ";
    }
    console.log(message);

Console Commands

document.getElementsByName('year')[0]
year = document.getElementsByName('year')[0].value;

Comparisons

document.getElementsByName('year')[0].value == ""

Check Number Length

year.length
year.length == 4
!year.length == 4
!(year.length == 4)

Combining Expressions

if ((year == "") || !(year.length == 4))
    var year = document.getElementsByName('year')[0].value;
    if ((year == "") || !(year.length == 4)) {
        message += "The first appearance is required and must be a 4-digit year. ";
    }

Display Message

    var status = document.getElementById('status');
    if (message == "") {
        console.log('ready to submit');
    } else {
        status.firstElementChild.innerHTML = message;
        status.style.display = 'block';
    }

Deferred Submission

document.getElementsByName'add_hero')[0].submit()
                <input type="button" name="formSubmit" value="Add / Update Hero" onclick="verifyAddHero()">
                <input type="button" name="formSubmit" value="Add Appearance" onclick="verifyAddAppearance()">
                <input type="button" name="formSubmit" value="Delete Appearances" onclick="verifyDeleteAppearance()">
    switch ($_POST['formSubmit']) {
    var status = document.getElementById('status');
    if (message == "") {
        document.getElementsByName('add_hero')[0].submit();
    } else {
        status.firstElementChild.innerHTML = message;
        status.style.display = 'block';
    }

Selected Value

function verifyAddAppearance() {
    message = "";
}
                        <label>Hero</label>
                        <select name="alias">
                            <option value=""></option>
<?php
    // display list of heroes
    while($row = $hrslt->fetch()) {
?>
                            <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option>
<?php
    }
?>
                        </select>
alias = document.getElementsByName('alias')[1].value;

Not Equal

function verifyAddAppearance() {
    var message = "";
    var alias = document.getElementsByName('alias')[1].value;
    if (alias == "") {
        message += "The Hero is required. ";
    }
}

Checkbox Status

document.getElementById('movieList').getElementsByTagName('input')[1]
document.getElementById('movieList').getElementsByTagName('input')[1].checked

While Loop

    for (n = 0; n < movieList.length; n++) {
        
    }
    while((n < movieList.length) && (!movieList[n].checked)) {
        n++;
    }
    var message  = "";
    var noAppearance = 0;
    while((n < movieList.length) && (!movieList[n].checked)) {
        noAppearance++;
        n++;
    }
    if (noAppearance == movieList.length) {
        message += "You need to add at least one movie. ";
    }
movieList[movieList.length-2].checked
    if ((movieList[movieList.length-2].checked) && (movieList[movieList.length-1].value == "")) {
        message += "If you check the last box, you need to name the movie.";
    }
    var status = document.getElementById('status');
    if (message == "") {
        console.log('ready to submit');
    } else {
        status.firstElementChild.innerHTML = message;
        status.style.display = 'block';
    }

Sharing Code

function verifyAppearance() {
    var message  = "";
    var noAppearance = 0;
    var alias = document.getElementsByName('alias')[1].value;
    if (alias == "") {
        message += "The Hero is required. ";
    }
    var movieList = document.getElementById('movieList').getElementsByTagName('input');
    var n = 0;
    while((n < movieList.length) && (!movieList[n].checked)) {
        console.log(n);
        noAppearance++;
        n++;
    }
    console.log(noAppearance);
    if (noAppearance == movieList.length) {
        message += "You need to add at least one movie. ";
    }
    if ((movieList[movieList.length-2].checked) && (movieList[movieList.length-1].value == "")) {
        message += "If you check the last box, you need to name the movie.";
    }
    console.log(message);
}
function verifyAddAppearance() {
    // check form data
    verifyAppearance();

    // take action - display message or submit
    var status = document.getElementById('status');
    if (message == "") {
        console.log('ready to submit');
    } else {
        status.firstElementChild.innerHTML = message;
        status.style.display = 'block';
    }
}
    return(message);
    var message = verifyAppearance();

Uncheck Checkbox

function verifyDeleteAppearance() {
    // check form data
    var message = verifyAppearance();

    // take action - display message or submit
    var status = document.getElementById('status');
    if (message == "") {
        console.log('ready to submit');
    } else {
        status.firstElementChild.innerHTML = message;
        status.style.display = 'block';
    }
}
movieList[movieList.length-2].checked = false;
    // check form data
    var movieList = document.getElementById('movieList').getElementsByTagName('input');
    var message = verifyAppearance(movieList);
function verifyAppearance(movieList) {
    // uncheck 'new' checkbox
    movieList[movieList.length-2].checked = false;
        document.getElementsByName('add_appearance')[0].submit();
        document.getElementsByName('add_appearance')[0].submit();

Next: Exercises