0

I have been trying to set an event handlers in a Javascript file, without much success. Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Order your books!</title>
    <script type="text/javascript" src="scripts/Exercise2.js"></script>
</head>
<body>
    <h1>Order Books Online</h1>
    <fieldset>
        <form>
            <table>
                <tr>
                    <td><strong>Book</strong></td>
                    <td><strong>Quantity</strong></td>
                    <td><strong>Price</strong></td>
                </tr>
                <tr>
                    <td>Basic XHTML</td>
                    <td><input type="text" id="XHTML"/></td>
                    <td>$19.99</td>
                </tr>
                <tr>
                    <td>Intro to PHP</td>
                    <td><input type="text" id="PHP"/></td>
                    <td>$86.00</td>
                </tr>
                <tr>
                    <td>Advanced JQuery</td>
                    <td><input type="text" id="JQuery"/></td>
                    <td>$55.00</td>
                </tr>
            </table>
            <input type="submit" value="Place Order"/>
        </form>
    </fieldset>
</body>

And here is the Javascript:

var xhtml = document.getElementById("XHTML");
var php = document.getElementById("PHP");
var jquery = document.getElementById("JQuery");

function checkFields(field) {

    if (field.value === null) {

        alert("Please do not leave any field empty.");
    }
}

xhtml.onchange = checkFields(xhtml);
php.onchange = checkFields(php);
jquery.onchange = checkFields(jquery);

Now the console tells field is null, even when I try triggering the onchange by changing the value of the fields. What am I doing wrong?

Thanks.

C. Hennebelle
  • 41
  • 1
  • 6
  • Additionally, you have to assign a *function* to `onchange`. You are *immediately* calling `checkFields` and assigning its *return value* (which is `undefined`) – Quentin Mar 13 '16 at 17:35
  • 1
    https://jsfiddle.net/v9uL6gqj/ – Rayon Mar 13 '16 at 17:40

0 Answers0